From 22c8178dfbfc0a556b7082964741d14082fc4fa6 Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Sun, 3 Sep 2023 13:42:26 +0200 Subject: [PATCH] updated lecture notes --- doc/LectureNotes/exercisesweek36.ipynb | 393 ++++ doc/pub/week36/html/._week36-bs000.html | 147 +- doc/pub/week36/html/._week36-bs001.html | 164 +- doc/pub/week36/html/._week36-bs002.html | 147 +- doc/pub/week36/html/._week36-bs003.html | 179 +- doc/pub/week36/html/._week36-bs004.html | 203 +-- doc/pub/week36/html/._week36-bs005.html | 209 +-- doc/pub/week36/html/._week36-bs006.html | 253 +-- doc/pub/week36/html/._week36-bs007.html | 243 ++- doc/pub/week36/html/._week36-bs008.html | 216 ++- doc/pub/week36/html/._week36-bs009.html | 180 +- doc/pub/week36/html/._week36-bs010.html | 193 +- doc/pub/week36/html/._week36-bs011.html | 169 +- doc/pub/week36/html/._week36-bs012.html | 162 +- doc/pub/week36/html/._week36-bs013.html | 171 +- doc/pub/week36/html/._week36-bs014.html | 171 +- doc/pub/week36/html/._week36-bs015.html | 176 +- doc/pub/week36/html/._week36-bs016.html | 173 +- doc/pub/week36/html/._week36-bs017.html | 170 +- doc/pub/week36/html/._week36-bs018.html | 157 +- doc/pub/week36/html/._week36-bs019.html | 161 +- doc/pub/week36/html/._week36-bs020.html | 165 +- doc/pub/week36/html/._week36-bs021.html | 158 +- doc/pub/week36/html/._week36-bs022.html | 159 +- doc/pub/week36/html/._week36-bs023.html | 174 +- doc/pub/week36/html/._week36-bs024.html | 178 +- doc/pub/week36/html/._week36-bs025.html | 180 +- doc/pub/week36/html/._week36-bs026.html | 235 +-- doc/pub/week36/html/._week36-bs027.html | 171 +- doc/pub/week36/html/._week36-bs028.html | 209 +-- doc/pub/week36/html/._week36-bs029.html | 263 +-- doc/pub/week36/html/._week36-bs030.html | 176 +- doc/pub/week36/html/._week36-bs031.html | 220 +-- doc/pub/week36/html/._week36-bs032.html | 180 +- doc/pub/week36/html/._week36-bs033.html | 206 +-- doc/pub/week36/html/._week36-bs034.html | 221 ++- doc/pub/week36/html/._week36-bs035.html | 293 +-- doc/pub/week36/html/._week36-bs036.html | 269 +-- doc/pub/week36/html/._week36-bs037.html | 271 +-- doc/pub/week36/html/._week36-bs038.html | 171 +- doc/pub/week36/html/._week36-bs039.html | 207 +-- doc/pub/week36/html/._week36-bs040.html | 166 +- doc/pub/week36/html/._week36-bs041.html | 181 +- doc/pub/week36/html/._week36-bs042.html | 220 +-- doc/pub/week36/html/._week36-bs043.html | 171 +- doc/pub/week36/html/._week36-bs044.html | 183 +- doc/pub/week36/html/._week36-bs045.html | 187 +- doc/pub/week36/html/._week36-bs046.html | 180 +- doc/pub/week36/html/._week36-bs047.html | 267 +-- doc/pub/week36/html/._week36-bs048.html | 186 +- doc/pub/week36/html/._week36-bs049.html | 194 +- doc/pub/week36/html/._week36-bs050.html | 185 +- doc/pub/week36/html/week36-bs.html | 147 +- doc/pub/week36/html/week36-reveal.html | 771 +------- doc/pub/week36/html/week36-solarized.html | 751 +------- doc/pub/week36/html/week36.html | 751 +------- doc/pub/week36/ipynb/ipynb-week36-src.tar.gz | Bin 192 -> 192 bytes doc/pub/week36/ipynb/week36.ipynb | 1601 +++-------------- .../exercisesweek36-checkpoint.ipynb | 351 ++++ doc/src/week36/exercisesweek36.do.txt | 30 +- doc/src/week36/week36.do.txt | 618 +------ 61 files changed, 5198 insertions(+), 10085 deletions(-) create mode 100644 doc/LectureNotes/exercisesweek36.ipynb create mode 100644 doc/src/week36/.ipynb_checkpoints/exercisesweek36-checkpoint.ipynb diff --git a/doc/LectureNotes/exercisesweek36.ipynb b/doc/LectureNotes/exercisesweek36.ipynb new file mode 100644 index 000000000..04624a409 --- /dev/null +++ b/doc/LectureNotes/exercisesweek36.ipynb @@ -0,0 +1,393 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "6bb78ffe", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "a756b88a", + "metadata": { + "editable": true + }, + "source": [ + "# Exercises week 36\n", + "**September 4-8, 2023**\n", + "\n", + "Date: **Deadline is Sunday September 10 at midnight**" + ] + }, + { + "cell_type": "markdown", + "id": "4c64515c", + "metadata": { + "editable": true + }, + "source": [ + "## Overarching aims of the exercises this week\n", + "\n", + "This set of exercises form an important part of the first project. The\n", + "analytical exercises deal with the material covered last week on the\n", + "mathematical interpretations of ordinary least squares and of Ridge\n", + "regression. The numerical exercises can be seen as a continuation of\n", + "exercise 3 from week 35, with the inclusion of Ridge regression. This\n", + "material enters also the discussions of the first project." + ] + }, + { + "cell_type": "markdown", + "id": "6d83ecbd", + "metadata": { + "editable": true + }, + "source": [ + "## Exercise 1: Analytical exercises\n", + "\n", + "The aim here is to derive the expression for the optimal parameters\n", + "using Ridge regression. Furthermore, using the singular value\n", + "decomposition, we will analyze the difference between the ordinary\n", + "least squares approach and Ridge regression.\n", + "\n", + "The expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, was given by the\n", + "optimization problem" + ] + }, + { + "cell_type": "markdown", + "id": "96444623", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\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": "66ea8e0c", + "metadata": { + "editable": true + }, + "source": [ + "which we can also write as" + ] + }, + { + "cell_type": "markdown", + "id": "90823663", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", + "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "812b9485", + "metadata": { + "editable": true + }, + "source": [ + "where we have used the definition of a norm-2 vector, that is" + ] + }, + { + "cell_type": "markdown", + "id": "b0bf6d67", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "737ebbd9", + "metadata": { + "editable": true + }, + "source": [ + "By minimizing the above equation with respect to the parameters\n", + "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", + "parameters $\\boldsymbol{\\beta}$.\n", + "\n", + "We can add a regularization parameter $\\lambda$ by\n", + "defining a new cost function to be optimized, that is" + ] + }, + { + "cell_type": "markdown", + "id": "d0089b18", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", + "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "14388b10", + "metadata": { + "editable": true + }, + "source": [ + "which leads to the Ridge regression minimization problem. One can require as part of the optimization problem \n", + "that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", + "a finite number larger than zero. We will not implement that here." + ] + }, + { + "cell_type": "markdown", + "id": "a8bc91a0", + "metadata": { + "editable": true + }, + "source": [ + "### a) Expression for Ridge regression\n", + "\n", + "Show that the optimal parameters" + ] + }, + { + "cell_type": "markdown", + "id": "9652f49f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "80519c5d", + "metadata": { + "editable": true + }, + "source": [ + "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" + ] + }, + { + "cell_type": "markdown", + "id": "43f58011", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4f336993", + "metadata": { + "editable": true + }, + "source": [ + "with $t$ a finite positive number. \n", + "\n", + "The ordinary least squares result is" + ] + }, + { + "cell_type": "markdown", + "id": "b9dc87be", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7dc4483d", + "metadata": { + "editable": true + }, + "source": [ + "### b) The singular value decomposition\n", + "\n", + "Use the singular value decomposition of an n\\times p$ matrix $\\boldsymbol{X}$ (our design matrix)" + ] + }, + { + "cell_type": "markdown", + "id": "e45e9fa3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "acb74b76", + "metadata": { + "editable": true + }, + "source": [ + "where $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal matrices of dimensions\n", + "$n\\times n$ and $p\\times p$, respectively, and $\\boldsymbol{\\Sigma}$ is an\n", + "$n\\times p$ matrix which contains the ingular values only. This material was discussed during the lectures of week 35.\n", + "\n", + "Show that you can write the \n", + "OLS solutions in terms of the eigenvectors (the columns) of the orthogonal matrix $\\boldsymbol{U}$ as" + ] + }, + { + "cell_type": "markdown", + "id": "67537508", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} = \\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c2de46e7", + "metadata": { + "editable": true + }, + "source": [ + "For Ridge regression, show that the corresponding equation is" + ] + }, + { + "cell_type": "markdown", + "id": "0ead662e", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d8b43f14", + "metadata": { + "editable": true + }, + "source": [ + "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n", + "\n", + "Give an interpretation of the results. [Section 3.4 of Hastie et al's textbook gives a good discussion of the above results](https://link.springer.com/book/10.1007/978-0-387-84858-7)." + ] + }, + { + "cell_type": "markdown", + "id": "d90dde5d", + "metadata": { + "editable": true + }, + "source": [ + "## Exercise 2: Adding Ridge Regression\n", + "\n", + "This exercise is a continuation of exercise 3 from week 35, see . We will use the same function to\n", + "generate our data set, still staying with a simple function $y(x)$\n", + "which we want to fit using linear regression, but now extending the\n", + "analysis to include the Ridge regression method.\n", + "\n", + "In this exercise you need to include the same elements from last week, that is\n", + "1. scale your data by subtracting the mean value from each column in the design matrix.\n", + "\n", + "2. perform a split of the data in a training set and a test set.\n", + "\n", + "The addition to the analysis this time is the introduction of the hyperparameter $\\lambda$ when introducing Ridge regression.\n", + "\n", + "Extend the code from exercise 3 from [week 35](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek35.html) to include Ridge regression with the hyperparameter $\\lambda$. The optimal parameters $\\hat{\\beta}$ for Ridge regression can be obtained by matrix inversion in a similar way as done for ordinary least squares. You need to add to your code the following equations" + ] + }, + { + "cell_type": "markdown", + "id": "e303dad2", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4fa7dde4", + "metadata": { + "editable": true + }, + "source": [ + "The ordinary least squares result you encoded last week is given by" + ] + }, + { + "cell_type": "markdown", + "id": "1e1b12fc", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a6ea7503", + "metadata": { + "editable": true + }, + "source": [ + "Use these results to compute the mean squared error for ordinary least\n", + "squares and Ridge regression first for a polynomial of degree five\n", + "with $n=100$ data points and five selected values of\n", + "$\\lambda=[0.0001,0.001, 0.01,0.1,1.0]$. Compute thereafter the mean\n", + "squared error for the same values of $\\lambda$ for polynomials of degree ten\n", + "and $15$. Discuss your results for the training MSE and test MSE with\n", + "Ridge regression and ordinary least squares." + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/pub/week36/html/._week36-bs000.html b/doc/pub/week36/html/._week36-bs000.html index 12be7d203..631b17a9a 100644 --- a/doc/pub/week36/html/._week36-bs000.html +++ b/doc/pub/week36/html/._week36-bs000.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -313,7 +284,7 @@ MathJax.Hub.Config({
-

May 29, 2023

+

September 4-8, 2023


@@ -338,7 +309,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs001.html b/doc/pub/week36/html/._week36-bs001.html index d83f9eb68..0d9130960 100644 --- a/doc/pub/week36/html/._week36-bs001.html +++ b/doc/pub/week36/html/._week36-bs001.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -297,15 +268,18 @@ MathJax.Hub.Config({

    Plans for week 36

    - -

    Recommended Reading:

      -
    1. Lectures on Regression
    2. -
    3. Bishop 1.1, 1.2, 2.1, 2.2, 2.3 and 3.1
    4. -
    5. Hastie et al chapter 3
    6. +
    7. Material for the active learning sessions on Tuesday and Wednesday +
        +
      1. Summary from last week on discussion of SVD, Ridge and Lasso linear regression.
      2. +
      3. Recommended Reading: Hastie et al chapter 3, see https://link.springer.com/book/10.1007/978-0-387-84858-7
      4. +
      5. Presentation and discussion of first project
      6. +
      +
    8. Material for the lecture on Thursday September 7 +
        +
      1. Linear Regression and links with Statistics, Resampling methods
      2. +
      3. Recommended Reading: Hastie et al chapter 3, see https://link.springer.com/book/10.1007/978-0-387-84858-7
      4. +

    @@ -323,7 +297,7 @@ MathJax.Hub.Config({

  • 10
  • 11
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs002.html b/doc/pub/week36/html/._week36-bs002.html index 9e13c333e..339b2042a 100644 --- a/doc/pub/week36/html/._week36-bs002.html +++ b/doc/pub/week36/html/._week36-bs002.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,7 +266,7 @@ MathJax.Hub.Config({

     

     

     

    -

    Summary from last Week and discussion of SVD, Ridge and Lasso regression with examples

    +

    Material for the active learning sessions Tuesday and Wednesday

    @@ -314,7 +285,7 @@ MathJax.Hub.Config({

  • 11
  • 12
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs003.html b/doc/pub/week36/html/._week36-bs003.html index ff7746d93..dc3fca0e3 100644 --- a/doc/pub/week36/html/._week36-bs003.html +++ b/doc/pub/week36/html/._week36-bs003.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,39 +266,7 @@ MathJax.Hub.Config({

     

     

     

    -

    Linear Regression and the SVD

    - -

    We used the SVD to analyse the matrix to invert in ordinary lineat regression

    -$$ -\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T. -$$ - -

    Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined last week the matrix

    -$$ -\boldsymbol{\Sigma}^T\boldsymbol{\Sigma} = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\end{bmatrix}, -$$ - -

    where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is

    - -$$ -\tilde{\boldsymbol{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\ - 0 & \sigma_1 & 0 & \dots & 0 & 0 \\ - 0 & 0 & \sigma_2 & \dots & 0 & 0 \\ - 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\ - 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\ -\end{bmatrix}, -$$ - -

    meaning we can write

    -$$ -\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T. -$$ - -

    Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get

    -$$ -\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2. -$$ - +

    Summary from last Week and discussion of SVD, Ridge and Lasso regression with examples

    @@ -347,7 +286,7 @@ $$

  • 12
  • 13
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs004.html b/doc/pub/week36/html/._week36-bs004.html index 9ec432f70..0be0833a5 100644 --- a/doc/pub/week36/html/._week36-bs004.html +++ b/doc/pub/week36/html/._week36-bs004.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,45 +266,39 @@ MathJax.Hub.Config({

     

     

     

    -

    What does it mean?

    - -

    This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) -are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) with eigenvalues -given by the singular values squared, that is -

    +

    Linear Regression and the SVD

    +

    We used the SVD to analyse the matrix to invert in ordinary lineat regression

    $$ -\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2. +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T. $$ -

    In other words, each non-zero singular value of \( \boldsymbol{X} \) is a positive -square root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). It means also that -the columns of \( \boldsymbol{V} \) are the eigenvectors of -\( \boldsymbol{X}^T\boldsymbol{X} \). Since we have ordered the singular values of -\( \boldsymbol{X} \) in a descending order, it means that the column vectors -\( \boldsymbol{v}_i \) are hierarchically ordered by how much correlation they -encode from the columns of \( \boldsymbol{X} \). -

    - -

    Note that these are also the eigenvectors and eigenvalues of the -Hessian matrix. -

    - -

    If we now recall the definition of the covariance matrix (not using -Bessel's correction) we have -

    - +

    Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined last week the matrix

    $$ -\boldsymbol{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}, +\boldsymbol{\Sigma}^T\boldsymbol{\Sigma} = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\end{bmatrix}, +$$ + +

    where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is

    + +$$ +\tilde{\boldsymbol{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\ + 0 & \sigma_1 & 0 & \dots & 0 & 0 \\ + 0 & 0 & \sigma_2 & \dots & 0 & 0 \\ + 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\ + 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\ +\end{bmatrix}, +$$ + +

    meaning we can write

    +$$ +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T. +$$ + +

    Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get

    +$$ +\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2. $$ -

    meaning that every squared non-singular value of \( \boldsymbol{X} \) divided by \( n \) ( -the number of samples) are the eigenvalues of the covariance -matrix. Every singular value of \( \boldsymbol{X} \) is thus a positive square -root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). If the matrix \( \boldsymbol{X} \) is -self-adjoint, the singular values of \( \boldsymbol{X} \) are equal to the -absolute value of the eigenvalues of \( \boldsymbol{X} \). -

    @@ -354,7 +319,7 @@ absolute value of the eigenvalues of \( \boldsymbol{X} \).

  • 13
  • 14
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs005.html b/doc/pub/week36/html/._week36-bs005.html index 395ad8925..9f8cd178c 100644 --- a/doc/pub/week36/html/._week36-bs005.html +++ b/doc/pub/week36/html/._week36-bs005.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,38 +266,44 @@ MathJax.Hub.Config({

     

     

     

    -

    And finally \( \boldsymbol{X}\boldsymbol{X}^T \)

    +

    What does it mean?

    -

    For \( \boldsymbol{X}\boldsymbol{X}^T \) we found

    - -$$ -\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T=\boldsymbol{U}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{U}^T. -$$ - -

    Since the matrices here have dimension \( n\times n \), we have

    -$$ -\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \boldsymbol{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}, -$$ - -

    leading to

    -$$ -\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}\boldsymbol{U}^T. -$$ - -

    Multiplying with \( \boldsymbol{U} \) from the right gives us the eigenvalue problem

    -$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U}=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}. -$$ - -

    It means that the eigenvalues of \( \boldsymbol{X}\boldsymbol{X}^T \) are again given by -the non-zero singular values plus now a series of zeros. The column -vectors of \( \boldsymbol{U} \) are the eigenvectors of \( \boldsymbol{X}\boldsymbol{X}^T \) and -measure how much correlations are contained in the rows of \( \boldsymbol{X} \). +

    This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) +are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) with eigenvalues +given by the singular values squared, that is

    -

    Since we will mainly be interested in the correlations among the features -of our data (the columns of \( \boldsymbol{X} \), the quantity of interest for us are the non-zero singular -values and the column vectors of \( \boldsymbol{V} \). +$$ +\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2. +$$ + +

    In other words, each non-zero singular value of \( \boldsymbol{X} \) is a positive +square root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). It means also that +the columns of \( \boldsymbol{V} \) are the eigenvectors of +\( \boldsymbol{X}^T\boldsymbol{X} \). Since we have ordered the singular values of +\( \boldsymbol{X} \) in a descending order, it means that the column vectors +\( \boldsymbol{v}_i \) are hierarchically ordered by how much correlation they +encode from the columns of \( \boldsymbol{X} \). +

    + +

    Note that these are also the eigenvectors and eigenvalues of the +Hessian matrix. +

    + +

    If we now recall the definition of the covariance matrix (not using +Bessel's correction) we have +

    + +$$ +\boldsymbol{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}, +$$ + +

    meaning that every squared non-singular value of \( \boldsymbol{X} \) divided by \( n \) ( +the number of samples) are the eigenvalues of the covariance +matrix. Every singular value of \( \boldsymbol{X} \) is thus a positive square +root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). If the matrix \( \boldsymbol{X} \) is +self-adjoint, the singular values of \( \boldsymbol{X} \) are equal to the +absolute value of the eigenvalues of \( \boldsymbol{X} \).

    @@ -349,7 +326,7 @@ values and the column vectors of \( \boldsymbol{V} \).

  • 14
  • 15
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs006.html b/doc/pub/week36/html/._week36-bs006.html index 996408460..56e139918 100644 --- a/doc/pub/week36/html/._week36-bs006.html +++ b/doc/pub/week36/html/._week36-bs006.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,87 +266,39 @@ MathJax.Hub.Config({

     

     

     

    -

    Code for SVD and Inversion of Matrices

    +

    And finally \( \boldsymbol{X}\boldsymbol{X}^T \)

    -

    How do we use the SVD to invert a matrix \( \boldsymbol{X}^\boldsymbol{X} \) which is singular or near singular? -The simple answer is to use the linear algebra function for pseudoinvers, that is +

    For \( \boldsymbol{X}\boldsymbol{X}^T \) we found

    + +$$ +\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T=\boldsymbol{U}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{U}^T. +$$ + +

    Since the matrices here have dimension \( n\times n \), we have

    +$$ +\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \boldsymbol{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}, +$$ + +

    leading to

    +$$ +\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}\boldsymbol{U}^T. +$$ + +

    Multiplying with \( \boldsymbol{U} \) from the right gives us the eigenvalue problem

    +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U}=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}. +$$ + +

    It means that the eigenvalues of \( \boldsymbol{X}\boldsymbol{X}^T \) are again given by +the non-zero singular values plus now a series of zeros. The column +vectors of \( \boldsymbol{U} \) are the eigenvectors of \( \boldsymbol{X}\boldsymbol{X}^T \) and +measure how much correlations are contained in the rows of \( \boldsymbol{X} \).

    - -
    -
    -
    -
    -
    -
    Ainv = np.linlag.pinv(A)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD.

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -# SVD inversion
    -def SVDinv(A):
    -    ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
    -    SVD is numerically more stable than the inversion algorithms provided by
    -    numpy and scipy.linalg at the cost of being slower.
    -    '''
    -    U, s, VT = np.linalg.svd(A)
    -    print('test U')
    -    print( (np.transpose(U) @ U - U @np.transpose(U)))
    -    print('test VT')
    -    print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
    -
    -
    -    D = np.zeros((len(U),len(VT)))
    -    D = np.diag(s)
    -    UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
    -    return np.matmul(V,np.matmul(invD,UT))
    -
    -
    -#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
    -# Non-singular square matrix
    -X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
    -print(X)
    -A = np.transpose(X) @ X
    -# Brute force inversion
    -B = np.linalg.inv(A)  # here we could use np.linalg.pinv(A)
    -C = SVDinv(A)
    -print(np.abs(B-C))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - +

    Since we will mainly be interested in the correlations among the features +of our data (the columns of \( \boldsymbol{X} \), the quantity of interest for us are the non-zero singular +values and the column vectors of \( \boldsymbol{V} \). +

    @@ -398,7 +321,7 @@ C = SVDinv(A)

  • 15
  • 16
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs007.html b/doc/pub/week36/html/._week36-bs007.html index 3e6dd57ec..ac7e16b7e 100644 --- a/doc/pub/week36/html/._week36-bs007.html +++ b/doc/pub/week36/html/._week36-bs007.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,55 +266,72 @@ MathJax.Hub.Config({

     

     

     

    -

    Inverse of Rectangular Matrix

    +

    Code for SVD and Inversion of Matrices

    -

    Although our matrix to invert \( \boldsymbol{X}^T\boldsymbol{X} \) is a square matrix, our matrix may be singular.

    - -

    The pseudoinverse is the generalization of the matrix inverse for square matrices to -rectangular matrices where the number of rows and columns are not equal. +

    How do we use the SVD to invert a matrix \( \boldsymbol{X}^\boldsymbol{X} \) which is singular or near singular? +The simple answer is to use the linear algebra function for pseudoinvers, that is

    -

    It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse. -It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices. -

    - -

    Using the SVD we can obtain the pseudoinverse of a matrix \( \boldsymbol{A} \) (labeled here as \( \boldsymbol{A}_{\mathrm{PI}} \))

    -$$ -\boldsymbol{A}_{\mathrm{PI}}= \boldsymbol{V}\boldsymbol{D}_{\mathrm{PI}}\boldsymbol{U}^T, -$$ - -

    where \( \boldsymbol{D}_{\mathrm{PI}} \) can be calculated by creating a diagonal matrix from \( \boldsymbol{\Sigma} \) where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD.

    - -
    -
    import numpy as np
    -# SVD inversion
    -def SVDinv(A):
    -    U, s, VT = np.linalg.svd(A)
    -    # reciprocals of singular values of s
    -    d = 1.0 / s
    -    # create m x n D matrix
    -    D = np.zeros(A.shape)
    -    # populate D with n x n diagonal matrix
    -    D[:A.shape[1], :A.shape[1]] = np.diag(d)
    -    UT = np.transpose(U)
    -    V = np.transpose(VT)
    -    return np.matmul(V,np.matmul(D.T,UT))
    -
    -
    -A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])
    -print(A)
    -# Brute force inversion of super-collinear matrix
    -B = np.linalg.pinv(A)
    -print(B)
    -# Compare our own algorithm with pinv
    -C = SVDinv(A)
    -print(np.abs(C-B))
    +  
    Ainv = np.linlag.pinv(A)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD.

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +# SVD inversion
    +def SVDinv(A):
    +    ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
    +    SVD is numerically more stable than the inversion algorithms provided by
    +    numpy and scipy.linalg at the cost of being slower.
    +    '''
    +    U, s, VT = np.linalg.svd(A)
    +    print('test U')
    +    print( (np.transpose(U) @ U - U @np.transpose(U)))
    +    print('test VT')
    +    print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
    +
    +
    +    D = np.zeros((len(U),len(VT)))
    +    D = np.diag(s)
    +    UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
    +    return np.matmul(V,np.matmul(invD,UT))
    +
    +
    +#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
    +# Non-singular square matrix
    +X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
    +print(X)
    +A = np.transpose(X) @ X
    +# Brute force inversion
    +B = np.linalg.inv(A)  # here we could use np.linalg.pinv(A)
    +C = SVDinv(A)
    +print(np.abs(B-C))
     
    @@ -359,7 +347,6 @@ C = SVDinv(A)
    -

    As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by Numpy.

    @@ -383,7 +370,7 @@ C = SVDinv(A)

  • 16
  • 17
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs008.html b/doc/pub/week36/html/._week36-bs008.html index ecd6ed89f..286d1e277 100644 --- a/doc/pub/week36/html/._week36-bs008.html +++ b/doc/pub/week36/html/._week36-bs008.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,26 +266,71 @@ MathJax.Hub.Config({

     

     

     

    -

    Ridge and LASSO Regression

    +

    Inverse of Rectangular Matrix

    -

    Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is -our optimization problem is +

    Although our matrix to invert \( \boldsymbol{X}^T\boldsymbol{X} \) is a square matrix, our matrix may be singular.

    + +

    The pseudoinverse is the generalization of the matrix inverse for square matrices to +rectangular matrices where the number of rows and columns are not equal.

    + +

    It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse. +It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices. +

    + +

    Using the SVD we can obtain the pseudoinverse of a matrix \( \boldsymbol{A} \) (labeled here as \( \boldsymbol{A}_{\mathrm{PI}} \))

    $$ -{\displaystyle \min_{\boldsymbol{\beta}\in {\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\}. +\boldsymbol{A}_{\mathrm{PI}}= \boldsymbol{V}\boldsymbol{D}_{\mathrm{PI}}\boldsymbol{U}^T, $$ -

    or we can state it as

    -$$ -{\displaystyle \min_{\boldsymbol{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2, -$$ +

    where \( \boldsymbol{D}_{\mathrm{PI}} \) can be calculated by creating a diagonal matrix from \( \boldsymbol{\Sigma} \) where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD.

    -

    where we have used the definition of a norm-2 vector, that is

    -$$ -\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. -$$ + +
    +
    +
    +
    +
    +
    import numpy as np
    +# SVD inversion
    +def SVDinv(A):
    +    U, s, VT = np.linalg.svd(A)
    +    # reciprocals of singular values of s
    +    d = 1.0 / s
    +    # create m x n D matrix
    +    D = np.zeros(A.shape)
    +    # populate D with n x n diagonal matrix
    +    D[:A.shape[1], :A.shape[1]] = np.diag(d)
    +    UT = np.transpose(U)
    +    V = np.transpose(VT)
    +    return np.matmul(V,np.matmul(D.T,UT))
    +
    +
    +A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])
    +print(A)
    +# Brute force inversion of super-collinear matrix
    +B = np.linalg.pinv(A)
    +print(B)
    +# Compare our own algorithm with pinv
    +C = SVDinv(A)
    +print(np.abs(C-B))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by Numpy.

    @@ -339,7 +355,7 @@ $$

  • 17
  • 18
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs009.html b/doc/pub/week36/html/._week36-bs009.html index 561a90d58..7460f374b 100644 --- a/doc/pub/week36/html/._week36-bs009.html +++ b/doc/pub/week36/html/._week36-bs009.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,39 +266,24 @@ MathJax.Hub.Config({

     

     

     

    -

    From OLS to Ridge and Lasso

    +

    Ridge and LASSO Regression

    -

    By minimizing the above equation with respect to the parameters -\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the -parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by -defining a new cost function to be optimized, that is +

    Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is +our optimization problem is

    +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in {\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\}. +$$ +

    or we can state it as

    $$ {\displaystyle \min_{\boldsymbol{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2 +{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2, $$ -

    which leads to the Ridge regression minimization problem where we -require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is -a finite number larger than zero. By defining -

    - +

    where we have used the definition of a norm-2 vector, that is

    $$ -C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1, -$$ - -

    we have a new optimization equation

    -$$ -{\displaystyle \min_{\boldsymbol{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1 -$$ - -

    which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.

    - -

    Here we have defined the norm-1 as

    -$$ -\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert. +\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. $$ @@ -355,7 +311,7 @@ $$
  • 18
  • 19
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs010.html b/doc/pub/week36/html/._week36-bs010.html index 7e6571fdf..cb9f625ac 100644 --- a/doc/pub/week36/html/._week36-bs010.html +++ b/doc/pub/week36/html/._week36-bs010.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,31 +266,41 @@ MathJax.Hub.Config({

     

     

     

    -

    Deriving the Ridge Regression Equations

    +

    From OLS to Ridge and Lasso

    -

    Using the matrix-vector expression for Ridge regression and dropping the parameter \( 1/n \) in front of the standard means squared error equation, we have

    - -$$ -C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta}, -$$ - -

    and -taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then -a slightly modified matrix inversion problem which for finite values -of \( \lambda \) does not suffer from singularity problems. We obtain -the optimal parameters +

    By minimizing the above equation with respect to the parameters +\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the +parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by +defining a new cost function to be optimized, that is

    -$$ -\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, -$$ - -

    with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that

    $$ -\sum_{i=0}^{p-1} \beta_i^2 \leq t, +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2 +$$ + +

    which leads to the Ridge regression minimization problem where we +require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is +a finite number larger than zero. By defining +

    + +$$ +C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1, +$$ + +

    we have a new optimization equation

    +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1 +$$ + +

    which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.

    + +

    Here we have defined the norm-1 as

    +$$ +\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert. $$ -

    with \( t \) a finite positive number.

    @@ -346,7 +327,7 @@ $$

  • 19
  • 20
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs011.html b/doc/pub/week36/html/._week36-bs011.html index 899897538..caf754da8 100644 --- a/doc/pub/week36/html/._week36-bs011.html +++ b/doc/pub/week36/html/._week36-bs011.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,15 +266,31 @@ MathJax.Hub.Config({

     

     

     

    -

    Note on Scikit-Learn

    +

    Deriving the Ridge Regression Equations

    -

    Note well that a library like Scikit-Learn does not include the \( 1/n \) factor in the expression for the mean-squared error. If you include it, the optimal parameter \( \beta \) becomes

    +

    Using the matrix-vector expression for Ridge regression and dropping the parameter \( 1/n \) in front of the standard means squared error equation, we have

    $$ -\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+n\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta}, $$ -

    In our codes where we compare our own codes with Scikit-Learn, we do thus not include the \( 1/n \) factor in the cost function.

    +

    and +taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then +a slightly modified matrix inversion problem which for finite values +of \( \lambda \) does not suffer from singularity problems. We obtain +the optimal parameters +

    +$$ +\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, +$$ + +

    with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that

    + +$$ +\sum_{i=0}^{p-1} \beta_i^2 \leq t, +$$ + +

    with \( t \) a finite positive number.

    @@ -330,7 +317,7 @@ $$

  • 20
  • 21
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs012.html b/doc/pub/week36/html/._week36-bs012.html index 2b98d7995..70bad9aa6 100644 --- a/doc/pub/week36/html/._week36-bs012.html +++ b/doc/pub/week36/html/._week36-bs012.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,20 +266,15 @@ MathJax.Hub.Config({

     

     

     

    -

    Comparison with OLS

    -

    When we compare this with the ordinary least squares result we have

    +

    Note on Scikit-Learn

    + +

    Note well that a library like Scikit-Learn does not include the \( 1/n \) factor in the expression for the mean-squared error. If you include it, the optimal parameter \( \beta \) becomes

    + $$ -\hat{\boldsymbol{\beta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, +\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+n\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -

    which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \).

    - -

    We see that Ridge regression is nothing but the standard OLS with a -modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The consequences, in -particular for our discussion of the bias-variance tradeoff are rather -interesting. We will see that for specific values of \( \lambda \), we may -even reduce the variance of the optimal parameters \( \boldsymbol{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here. -

    +

    In our codes where we compare our own codes with Scikit-Learn, we do thus not include the \( 1/n \) factor in the cost function.

    @@ -335,7 +301,7 @@ even reduce the variance of the optimal parameters \( \boldsymbol{\beta} \). The

  • 21
  • 22
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs013.html b/doc/pub/week36/html/._week36-bs013.html index 66d60dfed..d47203b50 100644 --- a/doc/pub/week36/html/._week36-bs013.html +++ b/doc/pub/week36/html/._week36-bs013.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,22 +266,20 @@ MathJax.Hub.Config({

     

     

     

    -

    SVD analysis

    +

    Comparison with OLS

    +

    When we compare this with the ordinary least squares result we have

    +$$ +\hat{\boldsymbol{\beta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, +$$ -

    Using our insights about the SVD of the design matrix \( \boldsymbol{X} \) -We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as +

    which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \).

    + +

    We see that Ridge regression is nothing but the standard OLS with a +modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The consequences, in +particular for our discussion of the bias-variance tradeoff are rather +interesting. We will see that for specific values of \( \lambda \), we may +even reduce the variance of the optimal parameters \( \boldsymbol{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.

    -$$ -\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. -$$ - -

    For Ridge regression this becomes

    - -$$ -\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{\Sigma}^2\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y}, -$$ - -

    with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \) from the SVD of the matrix \( \boldsymbol{X} \).

    @@ -337,7 +306,7 @@ $$

  • 22
  • 23
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs014.html b/doc/pub/week36/html/._week36-bs014.html index 5b829507f..2011218fb 100644 --- a/doc/pub/week36/html/._week36-bs014.html +++ b/doc/pub/week36/html/._week36-bs014.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,22 +266,22 @@ MathJax.Hub.Config({

     

     

     

    -

    Interpreting the Ridge results

    +

    SVD analysis

    -

    Since \( \lambda \geq 0 \), it means that compared to OLS, we have

    - -$$ -\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. -$$ - -

    Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the -orthonormal basis \( \boldsymbol{U} \), it then shrinks the coordinates by -\( \frac{\sigma_j^2}{\sigma_j^2+\lambda} \). Recall that the SVD has -eigenvalues ordered in a descending way, that is \( \sigma_i \geq -\sigma_{i+1} \). +

    Using our insights about the SVD of the design matrix \( \boldsymbol{X} \) +We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as

    +$$ +\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. +$$ -

    For small eigenvalues \( \sigma_i \) it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.

    +

    For Ridge regression this becomes

    + +$$ +\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{\Sigma}^2\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y}, +$$ + +

    with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \) from the SVD of the matrix \( \boldsymbol{X} \).

    @@ -337,7 +308,7 @@ eigenvalues ordered in a descending way, that is \( \sigma_i \geq

  • 23
  • 24
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs015.html b/doc/pub/week36/html/._week36-bs015.html index e4c997e23..17a131ec9 100644 --- a/doc/pub/week36/html/._week36-bs015.html +++ b/doc/pub/week36/html/._week36-bs015.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,35 +266,22 @@ MathJax.Hub.Config({

     

     

     

    -

    More interpretations

    +

    Interpreting the Ridge results

    -

    For the sake of simplicity, let us assume that the design matrix is orthonormal, that is

    +

    Since \( \lambda \geq 0 \), it means that compared to OLS, we have

    $$ -\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. +\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. $$ -

    In this case the standard OLS results in

    -$$ -\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y}, -$$ - -

    and

    - -$$ -\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}}, -$$ - -

    that is the Ridge estimator scales the OLS estimator by the inverse of a factor \( 1+\lambda \), and -the Ridge estimator converges to zero when the hyperparameter goes to -infinity. +

    Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the +orthonormal basis \( \boldsymbol{U} \), it then shrinks the coordinates by +\( \frac{\sigma_j^2}{\sigma_j^2+\lambda} \). Recall that the SVD has +eigenvalues ordered in a descending way, that is \( \sigma_i \geq +\sigma_{i+1} \).

    -

    We will come back to more interpreations after we have gone through some of the statistical analysis part.

    - -

    For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. -Similarly, Mehta et al's article is also recommended. -

    +

    For small eigenvalues \( \sigma_i \) it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.

    @@ -350,7 +308,7 @@ Similarly, Mehta et al

  • 24
  • 25
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs016.html b/doc/pub/week36/html/._week36-bs016.html index e914af0f0..a214de1a3 100644 --- a/doc/pub/week36/html/._week36-bs016.html +++ b/doc/pub/week36/html/._week36-bs016.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,31 +266,35 @@ MathJax.Hub.Config({

     

     

     

    -

    Deriving the Lasso Regression Equations

    +

    More interpretations

    -

    Using the matrix-vector expression for Lasso regression and dropping the parameter \( 1/n \) in front of the standard mean squared error equation, we have the following cost function

    +

    For the sake of simplicity, let us assume that the design matrix is orthonormal, that is

    $$ -C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1, +\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. $$ -

    Taking the derivative with respect to \( \boldsymbol{\beta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)

    +

    In this case the standard OLS results in

    $$ -\frac{d \vert \beta\vert}{d \boldsymbol{\beta}}=\mathrm{sgn}(\boldsymbol{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\-1 & \beta < 0, \end{array}\right. +\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y}, $$ -

    we have that the derivative of the cost function is

    +

    and

    $$ -\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-2\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0, +\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}}, $$ -

    and reordering we have

    -$$ -\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=2\boldsymbol{X}^T\boldsymbol{y}. -$$ +

    that is the Ridge estimator scales the OLS estimator by the inverse of a factor \( 1+\lambda \), and +the Ridge estimator converges to zero when the hyperparameter goes to +infinity. +

    -

    This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package CVXOPT. We will discuss this later.

    +

    We will come back to more interpreations after we have gone through some of the statistical analysis part.

    + +

    For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. +Similarly, Mehta et al's article is also recommended. +

    @@ -346,7 +321,7 @@ $$

  • 25
  • 26
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs017.html b/doc/pub/week36/html/._week36-bs017.html index 43a007fee..fa2df0757 100644 --- a/doc/pub/week36/html/._week36-bs017.html +++ b/doc/pub/week36/html/._week36-bs017.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,22 +266,31 @@ MathJax.Hub.Config({

     

     

     

    -

    Simple example to illustrate Ordinary Least Squares, Ridge and Lasso Regression

    +

    Deriving the Lasso Regression Equations

    -

    Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the -diagonal. In this case we have an equal number of rows and columns \( n=p \). -

    +

    Using the matrix-vector expression for Lasso regression and dropping the parameter \( 1/n \) in front of the standard mean squared error equation, we have the following cost function

    -

    Our model approximation is just \( \tilde{\boldsymbol{y}}=\boldsymbol{\beta} \) and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term \( 1/n \))

    $$ -C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2, +C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1, $$ -

    and minimizing we have that

    +

    Taking the derivative with respect to \( \boldsymbol{\beta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)

    $$ -\hat{\beta}_i^{\mathrm{OLS}} = y_i. +\frac{d \vert \beta\vert}{d \boldsymbol{\beta}}=\mathrm{sgn}(\boldsymbol{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\-1 & \beta < 0, \end{array}\right. $$ +

    we have that the derivative of the cost function is

    + +$$ +\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-2\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0, +$$ + +

    and reordering we have

    +$$ +\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=2\boldsymbol{X}^T\boldsymbol{y}. +$$ + +

    This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package CVXOPT. We will discuss this later.

    @@ -337,7 +317,7 @@ $$

  • 26
  • 27
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs018.html b/doc/pub/week36/html/._week36-bs018.html index 12a02f185..69366bf0d 100644 --- a/doc/pub/week36/html/._week36-bs018.html +++ b/doc/pub/week36/html/._week36-bs018.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,16 +266,20 @@ MathJax.Hub.Config({

     

     

     

    -

    Ridge Regression

    +

    Simple example to illustrate Ordinary Least Squares, Ridge and Lasso Regression

    -

    For Ridge regression our cost function is

    +

    Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the +diagonal. In this case we have an equal number of rows and columns \( n=p \). +

    + +

    Our model approximation is just \( \tilde{\boldsymbol{y}}=\boldsymbol{\beta} \) and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term \( 1/n \))

    $$ -C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2, +C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2, $$

    and minimizing we have that

    $$ -\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}. +\hat{\beta}_i^{\mathrm{OLS}} = y_i. $$ @@ -333,7 +308,7 @@ $$
  • 27
  • 28
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs019.html b/doc/pub/week36/html/._week36-bs019.html index 3589e887f..3a7946a6a 100644 --- a/doc/pub/week36/html/._week36-bs019.html +++ b/doc/pub/week36/html/._week36-bs019.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,26 +266,18 @@ MathJax.Hub.Config({

     

     

     

    -

    Lasso Regression

    +

    Ridge Regression

    -

    For Lasso regression our cost function is

    +

    For Ridge regression our cost function is

    $$ -C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\vert\beta_i\vert=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\sqrt{\beta_i^2}, +C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2, $$

    and minimizing we have that

    $$ --2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0, +\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}. $$ -

    which leads to

    -$$ -\hat{\boldsymbol{\beta}}_i^{\mathrm{Lasso}} = \left\{\begin{array}{ccc}y_i-\frac{\lambda}{2} &\mathrm{if} & y_i> \frac{\lambda}{2}\\ - y_i+\frac{\lambda}{2} &\mathrm{if} & y_i < -\frac{\lambda}{2}\\ - 0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\. -$$ - -

    Plotting these results (figure in handwritten notes for week 36) shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).

    @@ -341,7 +304,7 @@ $$

  • 28
  • 29
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs020.html b/doc/pub/week36/html/._week36-bs020.html index 1158ac94e..3fed3e28c 100644 --- a/doc/pub/week36/html/._week36-bs020.html +++ b/doc/pub/week36/html/._week36-bs020.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,20 +266,26 @@ MathJax.Hub.Config({

     

     

     

    -

    Yet another Example

    - -

    Let us assume we have a data set with outputs/targets given by the vector

    +

    Lasso Regression

    +

    For Lasso regression our cost function is

    $$ -\boldsymbol{y}=\begin{bmatrix}4 \\ 2 \\3\end{bmatrix}, +C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\vert\beta_i\vert=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\sqrt{\beta_i^2}, $$ -

    and our inputs as a \( 3\times 2 \) design matrix

    +

    and minimizing we have that

    $$ -\boldsymbol{X}=\begin{bmatrix}2 & 0\\ 0 & 1 \\ 0 & 0\end{bmatrix}, +-2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0, $$ -

    meaning that we have two features and two unknown parameters \( \beta_0 \) and \( \beta_1 \) to be determined either by ordinary least squares, Ridge or Lasso regression.

    +

    which leads to

    +$$ +\hat{\boldsymbol{\beta}}_i^{\mathrm{Lasso}} = \left\{\begin{array}{ccc}y_i-\frac{\lambda}{2} &\mathrm{if} & y_i> \frac{\lambda}{2}\\ + y_i+\frac{\lambda}{2} &\mathrm{if} & y_i < -\frac{\lambda}{2}\\ + 0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\. +$$ + +

    Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).

    @@ -335,7 +312,7 @@ $$

  • 29
  • 30
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs021.html b/doc/pub/week36/html/._week36-bs021.html index ce416353a..a6a9b0148 100644 --- a/doc/pub/week36/html/._week36-bs021.html +++ b/doc/pub/week36/html/._week36-bs021.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,21 +266,20 @@ MathJax.Hub.Config({

     

     

     

    -

    The OLS case

    +

    Yet another Example

    -

    For ordinary least squares (OLS) we know that the optimal solution is

    +

    Let us assume we have a data set with outputs/targets given by the vector

    $$ -\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left( \boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +\boldsymbol{y}=\begin{bmatrix}4 \\ 2 \\3\end{bmatrix}, $$ -

    Inserting the above values we obtain that

    - +

    and our inputs as a \( 3\times 2 \) design matrix

    $$ -\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\begin{bmatrix}2 \\ 2\end{bmatrix}, +\boldsymbol{X}=\begin{bmatrix}2 & 0\\ 0 & 1 \\ 0 & 0\end{bmatrix}, $$ -

    The code which implements this simpler case is presented after the discussion of Ridge and Lasso.

    +

    meaning that we have two features and two unknown parameters \( \beta_0 \) and \( \beta_1 \) to be determined either by ordinary least squares, Ridge or Lasso regression.

    @@ -336,7 +306,7 @@ $$

  • 30
  • 31
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs022.html b/doc/pub/week36/html/._week36-bs022.html index f074e3484..5a7129e54 100644 --- a/doc/pub/week36/html/._week36-bs022.html +++ b/doc/pub/week36/html/._week36-bs022.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,25 +266,21 @@ MathJax.Hub.Config({

     

     

     

    -

    The Ridge case

    +

    The OLS case

    -

    For Ridge regression we have

    +

    For ordinary least squares (OLS) we know that the optimal solution is

    $$ -\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\left( \boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left( \boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$

    Inserting the above values we obtain that

    $$ -\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\begin{bmatrix}\frac{8}{4+\lambda} \\ \frac{2}{1+\lambda}\end{bmatrix}, +\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\begin{bmatrix}2 \\ 2\end{bmatrix}, $$ -

    There is normally a constraint on the value of \( \vert\vert \boldsymbol{\beta}\vert\vert_2 \) via the parameter \( \lambda \). -Let us for simplicity assume that \( \beta_0^2+\beta_1^2=1 \) as constraint. This will allow us to find an expression for the optimal values of \( \beta \) and \( \lambda \). -

    - -

    To see this, let us write the cost function for Ridge regression.

    +

    The code which implements this simpler case is presented after the discussion of Ridge and Lasso.

    @@ -340,7 +307,7 @@ Let us for simplicity assume that \( \beta_0^2+\beta_1^2=1 \) as constraint. Thi

  • 31
  • 32
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs023.html b/doc/pub/week36/html/._week36-bs023.html index 3c8b0d906..fc7ed78e6 100644 --- a/doc/pub/week36/html/._week36-bs023.html +++ b/doc/pub/week36/html/._week36-bs023.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,34 +266,25 @@ MathJax.Hub.Config({

     

     

     

    -

    Writing the Cost Function

    - -

    We define the MSE without the \( 1/n \) factor and have then, using that

    -$$ -\boldsymbol{X}\boldsymbol{\beta}=\begin{bmatrix} 2\beta_0 \\ \beta_1 \\0 \end{bmatrix}, -$$ +

    The Ridge case

    +

    For Ridge regression we have

    $$ -C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\beta_0^2+\beta_1^2), +\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\left( \boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -

    and taking the derivative with respect to \( \beta_0 \) we get

    +

    Inserting the above values we obtain that

    + $$ -\beta_0=\frac{8}{4+\lambda}, +\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\begin{bmatrix}\frac{8}{4+\lambda} \\ \frac{2}{1+\lambda}\end{bmatrix}, $$ -

    and for \( \beta_1 \) we obtain

    -$$ -\beta_1=\frac{2}{1+\lambda}, -$$ +

    There is normally a constraint on the value of \( \vert\vert \boldsymbol{\beta}\vert\vert_2 \) via the parameter \( \lambda \). +Let us for simplicity assume that \( \beta_0^2+\beta_1^2=1 \) as constraint. This will allow us to find an expression for the optimal values of \( \beta \) and \( \lambda \). +

    -

    Using the constraint for \( \beta_0^2+\beta_1^2=1 \) we can constrain \( \lambda \) by solving

    -$$ -\left(\frac{8}{4+\lambda}\right)^2+\left(\frac{2}{1+\lambda}\right)^2=1, -$$ - -

    which gives \( \lambda=4.571 \) and \( \beta_0=0.933 \) and \( \beta_1=0.359 \).

    +

    To see this, let us write the cost function for Ridge regression.

    @@ -349,7 +311,7 @@ $$

  • 32
  • 33
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs024.html b/doc/pub/week36/html/._week36-bs024.html index 312eb3626..edd80feda 100644 --- a/doc/pub/week36/html/._week36-bs024.html +++ b/doc/pub/week36/html/._week36-bs024.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,32 +266,35 @@ MathJax.Hub.Config({

     

     

     

    -

    Lasso case

    +

    Writing the Cost Function

    -

    For Lasso we need now, keeping a constraint on \( \vert\beta_0\vert+\vert\beta_1\vert=1 \), to take the derivative of the absolute values of \( \beta_0 \) -and \( \beta_1 \). This gives us the following derivatives of the cost function -

    +

    We define the MSE without the \( 1/n \) factor and have then, using that

    $$ -C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\vert\beta_0\vert+\vert\beta_1\vert), +\boldsymbol{X}\boldsymbol{\beta}=\begin{bmatrix} 2\beta_0 \\ \beta_1 \\0 \end{bmatrix}, $$ $$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_0}=-4(4-2\beta_0)+\lambda\mathrm{sgn}(\beta_0)=0, +C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\beta_0^2+\beta_1^2), $$ -

    and

    +

    and taking the derivative with respect to \( \beta_0 \) we get

    $$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_1}=-2(2-\beta_1)+\lambda\mathrm{sgn}(\beta_1)=0. +\beta_0=\frac{8}{4+\lambda}, $$ -

    We have now four cases to solve besides the trivial cases \( \beta_0 \) and/or \( \beta_1 \) are zero, namely

    -
      -
    1. \( \beta_0 > 0 \) and \( \beta_1 > 0 \),
    2. -
    3. \( \beta_0 > 0 \) and \( \beta_1 < 0 \),
    4. -
    5. \( \beta_0 < 0 \) and \( \beta_1 > 0 \),
    6. -
    7. \( \beta_0 < 0 \) and \( \beta_1 < 0 \).
    8. -
    +

    and for \( \beta_1 \) we obtain

    +$$ +\beta_1=\frac{2}{1+\lambda}, +$$ + +

    Using the constraint for \( \beta_0^2+\beta_1^2=1 \) we can constrain \( \lambda \) by solving

    +$$ +\left(\frac{8}{4+\lambda}\right)^2+\left(\frac{2}{1+\lambda}\right)^2=1, +$$ + +

    which gives \( \lambda=4.571 \) and \( \beta_0=0.933 \) and \( \beta_1=0.359 \).

    +

    diff --git a/doc/pub/week36/html/._week36-bs025.html b/doc/pub/week36/html/._week36-bs025.html index 69a2195ae..4350d5a77 100644 --- a/doc/pub/week36/html/._week36-bs025.html +++ b/doc/pub/week36/html/._week36-bs025.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,31 +266,32 @@ MathJax.Hub.Config({

     

     

     

    -

    The first Case

    +

    Lasso case

    -

    If we consider the first case, we have then

    +

    For Lasso we need now, keeping a constraint on \( \vert\beta_0\vert+\vert\beta_1\vert=1 \), to take the derivative of the absolute values of \( \beta_0 \) +and \( \beta_1 \). This gives us the following derivatives of the cost function +

    $$ --4(4-2\beta_0)+\lambda=0, +C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\vert\beta_0\vert+\vert\beta_1\vert), +$$ + + +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_0}=-4(4-2\beta_0)+\lambda\mathrm{sgn}(\beta_0)=0, $$

    and

    $$ --2(2-\beta_1)+\lambda=0. +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_1}=-2(2-\beta_1)+\lambda\mathrm{sgn}(\beta_1)=0. $$ -

    which yields

    - -$$ -\beta_0=\frac{16+\lambda}{8}, -$$ - -

    and

    -$$ -\beta_1=\frac{4+\lambda}{2}. -$$ - -

    Using the constraint on \( \beta_0 \) and \( \beta_1 \) we can then find the optimal value of \( \lambda \) for the different cases. We leave this as an exercise to you.

    - +

    We have now four cases to solve besides the trivial cases \( \beta_0 \) and/or \( \beta_1 \) are zero, namely

    +
      +
    1. \( \beta_0 > 0 \) and \( \beta_1 > 0 \),
    2. +
    3. \( \beta_0 > 0 \) and \( \beta_1 < 0 \),
    4. +
    5. \( \beta_0 < 0 \) and \( \beta_1 > 0 \),
    6. +
    7. \( \beta_0 < 0 \) and \( \beta_1 < 0 \).
    8. +

    diff --git a/doc/pub/week36/html/._week36-bs026.html b/doc/pub/week36/html/._week36-bs026.html index f294e6484..8c26ecba7 100644 --- a/doc/pub/week36/html/._week36-bs026.html +++ b/doc/pub/week36/html/._week36-bs026.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,84 +266,30 @@ MathJax.Hub.Config({

     

     

     

    -

    Simple code for solving the above problem

    +

    The first Case

    -

    Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of \( \lambda \), meaning that we need to perform a search in order to find the optimal values.

    +

    If we consider the first case, we have then

    +$$ +-4(4-2\beta_0)+\lambda=0, +$$ -

    First we study and compare the OLS and Ridge results. The next code compares all three methods.

    +

    and

    +$$ +-2(2-\beta_1)+\lambda=0. +$$ +

    which yields

    - -
    -
    -
    -
    -
    -
    import os
    -import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    +$$
    +\beta_0=\frac{16+\lambda}{8},
    +$$
     
    -def R2(y_data, y_model):
    -    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    +

    and

    +$$ +\beta_1=\frac{4+\lambda}{2}. +$$ - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. - -X = np.array( [ [ 2, 0], [0, 1], [0,0]]) -y = np.array( [4, 2, 3]) - - -# matrix inversion to find beta -OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y -print(OLSbeta) -# and then make the prediction -ytildeOLS = X @ OLSbeta -print("Training MSE for OLS") -print(MSE(y,ytildeOLS)) -ypredictOLS = X @ OLSbeta - -# Repeat now for Ridge regression and various values of the regularization parameter -I = np.eye(2,2) -# Decide which values of lambda to use -nlambdas = 100 -MSEPredict = np.zeros(nlambdas) -lambdas = np.logspace(-4, 4, nlambdas) -for i in range(nlambdas): - lmb = lambdas[i] - Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y -# print(Ridgebeta) - # and then make the prediction - ypredictRidge = X @ Ridgebeta - MSEPredict[i] = MSE(y,ypredictRidge) -# print(MSEPredict[i]) - # Now plot the results -plt.figure() -plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train') -plt.xlabel('log10(lambda)') -plt.ylabel('MSE') -plt.legend() -plt.show() -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    We see here that we reach a plateau. What is actually happening?

    +

    Using the constraint on \( \beta_0 \) and \( \beta_1 \) we can then find the optimal value of \( \lambda \) for the different cases. We leave this as an exercise to you.

    @@ -399,7 +316,7 @@ plt.show()

  • 35
  • 36
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs027.html b/doc/pub/week36/html/._week36-bs027.html index e01086037..91da48db4 100644 --- a/doc/pub/week36/html/._week36-bs027.html +++ b/doc/pub/week36/html/._week36-bs027.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,7 +266,11 @@ MathJax.Hub.Config({

     

     

     

    -

    With Lasso Regression

    +

    Simple code for solving the above problem

    + +

    Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of \( \lambda \), meaning that we need to perform a search in order to find the optimal values.

    + +

    First we study and compare the OLS and Ridge results. The next code compares all three methods.

    @@ -308,7 +283,6 @@ MathJax.Hub.Config({ import numpy as np import pandas as pd import matplotlib.pyplot as plt -from sklearn import linear_model def R2(y_data, y_model): return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) @@ -337,25 +311,19 @@ ypredictOLS = X = np.eye(2,2) # Decide which values of lambda to use nlambdas = 100 -MSERidgePredict = np.zeros(nlambdas) -MSELassoPredict = np.zeros(nlambdas) +MSEPredict = np.zeros(nlambdas) lambdas = np.logspace(-4, 4, nlambdas) for i in range(nlambdas): lmb = lambdas[i] Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y - print(Ridgebeta) +# print(Ridgebeta) # and then make the prediction ypredictRidge = X @ Ridgebeta - MSERidgePredict[i] = MSE(y,ypredictRidge) - RegLasso = linear_model.Lasso(lmb) - RegLasso.fit(X,y) - ypredictLasso = RegLasso.predict(X) - print(RegLasso.coef_) - MSELassoPredict[i] = MSE(y,ypredictLasso) -# Now plot the results + MSEPredict[i] = MSE(y,ypredictRidge) +# print(MSEPredict[i]) + # Now plot the results plt.figure() -plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train') -plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train') +plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train') plt.xlabel('log10(lambda)') plt.ylabel('MSE') plt.legend() @@ -375,6 +343,7 @@ plt.show()
    +

    We see here that we reach a plateau. What is actually happening?

    @@ -401,7 +370,7 @@ plt.show()

  • 36
  • 37
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs028.html b/doc/pub/week36/html/._week36-bs028.html index 6dec31562..1ad6c5412 100644 --- a/doc/pub/week36/html/._week36-bs028.html +++ b/doc/pub/week36/html/._week36-bs028.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,7 +266,7 @@ MathJax.Hub.Config({

     

     

     

    -

    Another Example, now with a polynomial fit

    +

    With Lasso Regression

    @@ -308,7 +279,6 @@ MathJax.Hub.Config({ import numpy as np import pandas as pd import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split from sklearn import linear_model def R2(y_data, y_model): @@ -320,64 +290,43 @@ MathJax.Hub.Config({ # A seed just to ensure that the random numbers are the same for every run. # Useful for eventual debugging. -np.random.seed(3155) -x = np.random.rand(100) -y = 2.0+5*x*x+0.1*np.random.randn(100) +X = np.array( [ [ 2, 0], [0, 1], [0,0]]) +y = np.array( [4, 2, 3]) -# number of features p (here degree of polynomial -p = 3 -# The design matrix now as function of a given polynomial -X = np.zeros((len(x),p)) -X[:,0] = 1.0 -X[:,1] = x -X[:,2] = x*x -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # matrix inversion to find beta -OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train +OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y print(OLSbeta) # and then make the prediction -ytildeOLS = X_train @ OLSbeta +ytildeOLS = X @ OLSbeta print("Training MSE for OLS") -print(MSE(y_train,ytildeOLS)) -ypredictOLS = X_test @ OLSbeta -print("Test MSE OLS") -print(MSE(y_test,ypredictOLS)) +print(MSE(y,ytildeOLS)) +ypredictOLS = X @ OLSbeta -# Repeat now for Lasso and Ridge regression and various values of the regularization parameter -I = np.eye(p,p) +# Repeat now for Ridge regression and various values of the regularization parameter +I = np.eye(2,2) # Decide which values of lambda to use nlambdas = 100 -MSEPredict = np.zeros(nlambdas) -MSETrain = np.zeros(nlambdas) +MSERidgePredict = np.zeros(nlambdas) MSELassoPredict = np.zeros(nlambdas) -MSELassoTrain = np.zeros(nlambdas) lambdas = np.logspace(-4, 4, nlambdas) for i in range(nlambdas): lmb = lambdas[i] - Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train - # include lasso using Scikit-Learn - RegLasso = linear_model.Lasso(lmb) - RegLasso.fit(X_train,y_train) + Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y + print(Ridgebeta) # and then make the prediction - ytildeRidge = X_train @ Ridgebeta - ypredictRidge = X_test @ Ridgebeta - ytildeLasso = RegLasso.predict(X_train) - ypredictLasso = RegLasso.predict(X_test) - MSEPredict[i] = MSE(y_test,ypredictRidge) - MSETrain[i] = MSE(y_train,ytildeRidge) - MSELassoPredict[i] = MSE(y_test,ypredictLasso) - MSELassoTrain[i] = MSE(y_train,ytildeLasso) - + ypredictRidge = X @ Ridgebeta + MSERidgePredict[i] = MSE(y,ypredictRidge) + RegLasso = linear_model.Lasso(lmb) + RegLasso.fit(X,y) + ypredictLasso = RegLasso.predict(X) + print(RegLasso.coef_) + MSELassoPredict[i] = MSE(y,ypredictLasso) # Now plot the results plt.figure() -plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train') -plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test') -plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train') -plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test') - +plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train') +plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train') plt.xlabel('log10(lambda)') plt.ylabel('MSE') plt.legend() @@ -423,7 +372,7 @@ plt.show()
  • 37
  • 38
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs029.html b/doc/pub/week36/html/._week36-bs029.html index c649c8408..3a88b550e 100644 --- a/doc/pub/week36/html/._week36-bs029.html +++ b/doc/pub/week36/html/._week36-bs029.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,28 +266,108 @@ MathJax.Hub.Config({

     

     

     

    -

    To think about, first part

    +

    Another Example, now with a polynomial fit

    -

    When you are comparing your own code with for example Scikit-Learn's -library, there are some technicalities to keep in mind. The examples -here demonstrate some of these aspects with potential pitfalls. -

    -

    The discussion here focuses on the role of the intercept, how we can -set up the design matrix, what scaling we should use and other topics -which tend confuse us. -

    + +
    +
    +
    +
    +
    +
    import os
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from sklearn.model_selection import train_test_split
    +from sklearn import linear_model
    +
    +def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +
    +# A seed just to ensure that the random numbers are the same for every run.
    +# Useful for eventual debugging.
    +np.random.seed(3155)
    +
    +x = np.random.rand(100)
    +y = 2.0+5*x*x+0.1*np.random.randn(100)
    +
    +# number of features p (here degree of polynomial
    +p = 3
    +#  The design matrix now as function of a given polynomial
    +X = np.zeros((len(x),p))
    +X[:,0] = 1.0
    +X[:,1] = x
    +X[:,2] = x*x
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +
    +# matrix inversion to find beta
    +OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
    +print(OLSbeta)
    +# and then make the prediction
    +ytildeOLS = X_train @ OLSbeta
    +print("Training MSE for OLS")
    +print(MSE(y_train,ytildeOLS))
    +ypredictOLS = X_test @ OLSbeta
    +print("Test MSE OLS")
    +print(MSE(y_test,ypredictOLS))
    +
    +# Repeat now for Lasso and Ridge regression and various values of the regularization parameter
    +I = np.eye(p,p)
    +# Decide which values of lambda to use
    +nlambdas = 100
    +MSEPredict = np.zeros(nlambdas)
    +MSETrain = np.zeros(nlambdas)
    +MSELassoPredict = np.zeros(nlambdas)
    +MSELassoTrain = np.zeros(nlambdas)
    +lambdas = np.logspace(-4, 4, nlambdas)
    +for i in range(nlambdas):
    +    lmb = lambdas[i]
    +    Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
    +    # include lasso using Scikit-Learn
    +    RegLasso = linear_model.Lasso(lmb)
    +    RegLasso.fit(X_train,y_train)
    +    # and then make the prediction
    +    ytildeRidge = X_train @ Ridgebeta
    +    ypredictRidge = X_test @ Ridgebeta
    +    ytildeLasso = RegLasso.predict(X_train)
    +    ypredictLasso = RegLasso.predict(X_test)
    +    MSEPredict[i] = MSE(y_test,ypredictRidge)
    +    MSETrain[i] = MSE(y_train,ytildeRidge)
    +    MSELassoPredict[i] = MSE(y_test,ypredictLasso)
    +    MSELassoTrain[i] = MSE(y_train,ytildeLasso)
    +
    +# Now plot the results
    +plt.figure()
    +plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')
    +plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')
    +plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train')
    +plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test')
    +
    +plt.xlabel('log10(lambda)')
    +plt.ylabel('MSE')
    +plt.legend()
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    The intercept can be interpreted as the expected value of our -target/output variables when all other predictors are set to zero. -Thus, if we cannot assume that the expected outputs/targets are zero -when all predictors are zero (the columns in the design matrix), it -may be a bad idea to implement a model which penalizes the intercept. -Furthermore, in for example Ridge and Lasso regression, the default solutions -from the library Scikit-Learn (when not shrinking \( \beta_0 \)) for the unknown parameters -\( \boldsymbol{\beta} \), are derived under the assumption that both \( \boldsymbol{y} \) and -\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values. -

    @@ -343,7 +394,7 @@ from the library Scikit-Learn (when not shrinking \( \beta_0 \)) for the

  • 38
  • 39
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs030.html b/doc/pub/week36/html/._week36-bs030.html index 0e6419f88..a7a85d312 100644 --- a/doc/pub/week36/html/._week36-bs030.html +++ b/doc/pub/week36/html/._week36-bs030.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,36 +266,7 @@ MathJax.Hub.Config({

     

     

     

    -

    More thinking

    - -

    If our predictors represent different scales, then it is important to -standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each -column from the corresponding column and dividing the column with its -standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, -the results may differ. -

    - -

    The -Standadscaler -function in Scikit-Learn does this for us. For the data sets we -have been studying in our various examples, the data are in many cases -already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a -survey of your data, with a critical assessment of them in case you need to scale the data. -

    - -

    If you need to scale the data, not doing so will give an unfair -penalization of the parameters since their magnitude depends on the -scale of their corresponding predictor. -

    - -

    Suppose as an example that you -you have an input variable given by the heights of different persons. -Human height might be measured in inches or meters or -kilometers. If measured in kilometers, a standard linear regression -model with this predictor would probably give a much bigger -coefficient term, than if measured in millimeters. -This can clearly lead to problems in evaluating the cost/loss functions. -

    +

    Material for lecture Thursday September 7

    @@ -351,7 +293,7 @@ This can clearly lead to problems in evaluating the cost/loss functions.

  • 39
  • 40
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs031.html b/doc/pub/week36/html/._week36-bs031.html index f4b879d80..2046994df 100644 --- a/doc/pub/week36/html/._week36-bs031.html +++ b/doc/pub/week36/html/._week36-bs031.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -294,49 +265,50 @@ MathJax.Hub.Config({

     

     

     

    - -

    Still thinking

    + +

    Linking the regression analysis with a statistical interpretation

    -

    Keep in mind that when you transform your data set before training a model, the same transformation needs to be done -on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows +

    We will now couple the discussions of ordinary least squares, Ridge +and Lasso regression with a statistical interpretation, that is we +move from a linear algebra analysis to a statistical analysis. In +particular, we will focus on what the regularization terms can result +in. We will amongst other things show that the regularization +parameter can reduce considerably the variance of the parameters +\( \beta \).

    +

    The +advantage of doing linear regression is that we actually end up with +analytical expressions for several statistical quantities. +Standard least squares and Ridge regression allow us to +derive quantities like the variance and other expectation values in a +rather straightforward way. +

    - -
    -
    -
    -
    -
    -
    #Model training, we compute the mean value of y and X
    -y_train_mean = np.mean(y_train)
    -X_train_mean = np.mean(X_train,axis=0)
    -X_train = X_train - X_train_mean
    -y_train = y_train - y_train_mean
    +

    It is assumed that \( \varepsilon_i +\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are +independent, i.e.: +

    +$$ +\begin{align*} +\mbox{Cov}(\varepsilon_{i_1}, +\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} +& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. +\end{align*} +$$ -# The we fit our model with the training data -trained_model = some_model.fit(X_train,y_train) - - -#Model prediction, we need also to transform our data set used for the prediction. -X_test = X_test - X_train_mean #Use mean from training data -y_pred = trained_model(X_test) -y_pred = y_pred + y_train_mean -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

    The randomness of \( \varepsilon_i \) implies that +\( \mathbf{y}_i \) is also a random variable. In particular, +\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim +\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a +non-random scalar. To specify the parameters of the distribution of +\( \mathbf{y}_i \) we need to calculate its first two moments. +

    +

    Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The +notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the +row number \( i \) and perform a sum over all values \( p \). +

    @@ -363,7 +335,7 @@ y_pred = y_pred 40

  • 41
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs032.html b/doc/pub/week36/html/._week36-bs032.html index fde17c13b..b8c52f96a 100644 --- a/doc/pub/week36/html/._week36-bs032.html +++ b/doc/pub/week36/html/._week36-bs032.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,38 +266,21 @@ MathJax.Hub.Config({

     

     

     

    -

    What does centering (subtracting the mean values) mean mathematically?

    +

    Assumptions made

    -

    Let us try to understand what this may imply mathematically when we -subtract the mean values, also known as zero centering. For -simplicity, we will focus on ordinary regression, as done in the above example. -

    - -

    The cost/loss function for regression is

    -$$ -C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. -$$ - -

    Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.

    - -

    What we have done is to single out the \( \beta_0 \) term in the definition of the mean squared error (MSE). -The design matrix -\( X \) does in this case not contain any intercept column. -When we take the derivative with respect to \( \beta_0 \), we want the derivative to obey +

    The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off) +that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) +which describe our data

    $$ -\frac{\partial C}{\partial \beta_j} = 0, +\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} $$ -

    for all \( j \). For \( \beta_0 \) we have

    - +

    We approximate this function with our model from the solution of the linear regression equations, that is our +function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with +

    $$ -\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). -$$ - -

    Multiplying away the constant \( 2/n \), we obtain

    -$$ -\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. $$ @@ -355,7 +309,7 @@ $$
  • 41
  • 42
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs033.html b/doc/pub/week36/html/._week36-bs033.html index ad9dd29d6..87c2e199b 100644 --- a/doc/pub/week36/html/._week36-bs033.html +++ b/doc/pub/week36/html/._week36-bs033.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,45 +266,38 @@ MathJax.Hub.Config({

     

     

     

    -

    Further Manipulations

    +

    Expectation value and variance

    -

    Let us special first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \). -Our result for \( \beta_0 \) simplifies then to +

    We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \)

    +$$ +\begin{align*} +\mathbb{E}(y_i) & = +\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i) +\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, +\end{align*} +$$ + +

    while +its variance is

    $$ -n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. -$$ - -

    We obtain then

    -$$ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. -$$ - -

    If we define

    -$$ -\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, -$$ - -

    and if we define the mean value of the outputs as

    -$$ -\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, -$$ - -

    we have

    -$$ -\beta_0 = \mu_y - \beta_1\mu_{1}. -$$ - -

    In the general case, that is we have more parameters than \( \beta_0 \) and \( \beta_1 \), we have

    -$$ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. -$$ - -

    Replacing \( y_i \) with \( y_i - y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)

    -$$ -C(\boldsymbol{\beta}) = (\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta})^T(\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta}). +\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i +- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) - +[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, +\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ & += \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i +\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i, +\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 +\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + +\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 +\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, +\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. +\end{align*} $$ +

    Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with +mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD). +

    @@ -360,7 +324,7 @@ $$

  • 42
  • 43
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs034.html b/doc/pub/week36/html/._week36-bs034.html index 13a93dad3..a6f1249a7 100644 --- a/doc/pub/week36/html/._week36-bs034.html +++ b/doc/pub/week36/html/._week36-bs034.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,24 +266,82 @@ MathJax.Hub.Config({

     

     

     

    -

    Wrapping it up

    - -

    If we minimize with respect to \( \boldsymbol{\beta} \) we have then

    +

    Expectation value and variance for \( \boldsymbol{\beta} \)

    +

    With the OLS expressions for the optimal parameters \( \boldsymbol{\hat{\beta}} \) we can evaluate the expectation value

    $$ -\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, +\mathbb{E}(\boldsymbol{\hat{\beta}}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. $$ -

    where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \) -and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \). +

    This means that the estimator of the regression parameters is unbiased.

    + +

    We can also calculate the variance

    + +

    The variance of the optimal value \( \boldsymbol{\hat{\beta}} \) is

    +$$ +\begin{eqnarray*} +\mbox{Var}(\boldsymbol{\hat{\beta}}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \} +\\ +& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \} +\\ +% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1} +% \\ +% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T +\\ +& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}, +\end{eqnarray*} +$$ + +

    where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) = +\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + +\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2 +\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the +variance of the estimate of the \( j \)-th regression coefficient: +\( \boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \). This may be used to +construct a confidence interval for the estimates.

    -

    For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then

    +

    In a similar way, we can obtain analytical expressions for say the +expectation values of the parameters \( \boldsymbol{\beta} \) and their variance +when we employ Ridge regression, allowing us again to define a confidence interval. +

    + +

    It is rather straightforward to show that

    $$ -\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}. +\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}. $$ -

    What does this mean? And why do we insist on all this? Let us look at some examples.

    +

    We see clearly that +\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased. +

    + +

    We can also compute the variance as

    + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +$$ + +

    and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero.

    + +

    With this, we can compute the difference

    + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. +$$ + +

    The difference is non-negative definite since each component of the +matrix product is non-negative definite. +This means the variance we obtain with the standard OLS will always for \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. +

    @@ -339,7 +368,7 @@ $$

  • 43
  • 44
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs035.html b/doc/pub/week36/html/._week36-bs035.html index 64ff998bf..c048ab677 100644 --- a/doc/pub/week36/html/._week36-bs035.html +++ b/doc/pub/week36/html/._week36-bs035.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,149 +266,27 @@ MathJax.Hub.Config({

     

     

     

    -

    Linear Regression code, Intercept handling first

    +

    Deriving OLS from a probability distribution

    -

    This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (code example thanks to Øyvind Sigmundson Schøyen). Here our scaling of the data is done by subtracting the mean values only. -Note also that we do not split the data into training and test. +

    Our basic assumption when we derived the OLS equations was to assume +that our output is determined by a given continuous function +\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal +distribution with zero mean value and an undetermined variance +\( \sigma^2 \).

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import matplotlib.pyplot as plt
    -
    -from sklearn.linear_model import LinearRegression
    -
    -
    -np.random.seed(2021)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -
    -def fit_beta(X, y):
    -    return np.linalg.pinv(X.T @ X) @ X.T @ y
    -
    -
    -true_beta = [2, 0.5, 3.7]
    -
    -x = np.linspace(0, 1, 11)
    -y = np.sum(
    -    np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0
    -) + 0.1 * np.random.normal(size=len(x))
    -
    -degree = 3
    -X = np.zeros((len(x), degree))
    -
    -# Include the intercept in the design matrix
    -for p in range(degree):
    -    X[:, p] = x ** p
    -
    -beta = fit_beta(X, y)
    -
    -# Intercept is included in the design matrix
    -skl = LinearRegression(fit_intercept=False).fit(X, y)
    -
    -print(f"True beta: {true_beta}")
    -print(f"Fitted beta: {beta}")
    -print(f"Sklearn fitted beta: {skl.coef_}")
    -ypredictOwn = X @ beta
    -ypredictSKL = skl.predict(X)
    -print(f"MSE with intercept column")
    -print(MSE(y,ypredictOwn))
    -print(f"MSE with intercept column from SKL")
    -print(MSE(y,ypredictSKL))
    -
    -
    -plt.figure()
    -plt.scatter(x, y, label="Data")
    -plt.plot(x, X @ beta, label="Fit")
    -plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)")
    -
    -
    -# Do not include the intercept in the design matrix
    -X = np.zeros((len(x), degree - 1))
    -
    -for p in range(degree - 1):
    -    X[:, p] = x ** (p + 1)
    -
    -# Intercept is not included in the design matrix
    -skl = LinearRegression(fit_intercept=True).fit(X, y)
    -
    -# Use centered values for X and y when computing coefficients
    -y_offset = np.average(y, axis=0)
    -X_offset = np.average(X, axis=0)
    -
    -beta = fit_beta(X - X_offset, y - y_offset)
    -intercept = np.mean(y_offset - X_offset @ beta)
    -
    -print(f"Manual intercept: {intercept}")
    -print(f"Fitted beta (wiothout intercept): {beta}")
    -print(f"Sklearn intercept: {skl.intercept_}")
    -print(f"Sklearn fitted beta (without intercept): {skl.coef_}")
    -ypredictOwn = X @ beta
    -ypredictSKL = skl.predict(X)
    -print(f"MSE with Manual intercept")
    -print(MSE(y,ypredictOwn+intercept))
    -print(f"MSE with Sklearn intercept")
    -print(MSE(y,ypredictSKL))
    -
    -plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)")
    -plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)")
    -plt.grid()
    -plt.legend()
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    The intercept is the value of our output/target variable -when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case). +

    We found above that the outputs \( \boldsymbol{y} \) have a mean value given by +\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to +the design matrix are not stochastic variables, we can assume that the +probability distribution of our targets is also a normal distribution +but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a +single output \( y_i \) is given by the Gaussian distribution

    -

    Printing the MSE, we see first that both methods give the same MSE, as -they should. However, when we move to for example Ridge regression, -the way we treat the intercept may give a larger or smaller MSE, -meaning that the MSE can be penalized by the value of the -intercept. Not including the intercept in the fit, means that the -regularization term does not include \( \beta_0 \). For different values -of \( \lambda \), this may lead to differeing MSE values. -

    - -

    To remind the reader, the regularization term, with the intercept in Ridge regression is given by

    $$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, +y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. $$ -

    but when we take out the intercept, this equation becomes

    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. -$$ - -

    For Lasso regression we have

    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. -$$ - -

    It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get a MSE which then contains the intercept.

    @@ -464,7 +313,7 @@ $$

  • 44
  • 45
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs036.html b/doc/pub/week36/html/._week36-bs036.html index 7cda3efb7..3a1c6e633 100644 --- a/doc/pub/week36/html/._week36-bs036.html +++ b/doc/pub/week36/html/._week36-bs036.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,102 +266,38 @@ MathJax.Hub.Config({

     

     

     

    -

    Code Examples

    +

    Independent and Identically Distrubuted (iid)

    -

    Armed with this wisdom, we attempt first to simply set the intercept equal to False in our implementation of Ridge regression for our well-known vanilla data set.

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(3155)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)
    -
    -Maxpolydegree = 20
    -X = np.zeros((n,Maxpolydegree))
    -#We include explicitely the intercept column
    -for degree in range(Maxpolydegree):
    -    X[:,degree] = x**degree
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -p = Maxpolydegree
    -I = np.eye(p,p)
    -# Decide which values of lambda to use
    -nlambdas = 6
    -MSEOwnRidgePredict = np.zeros(nlambdas)
    -MSERidgePredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
    -    # Note: we include the intercept column and no scaling
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    # and then make the prediction
    -    ytildeOwnRidge = X_train @ OwnRidgeBeta
    -    ypredictOwnRidge = X_test @ OwnRidgeBeta
    -    ytildeRidge = RegRidge.predict(X_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    print("Beta values for own Ridge implementation")
    -    print(OwnRidgeBeta)
    -    print("Beta values for Scikit-Learn Ridge implementation")
    -    print(RegRidge.coef_)
    -    print("MSE values for own Ridge implementation")
    -    print(MSEOwnRidgePredict[i])
    -    print("MSE values for Scikit-Learn Ridge implementation")
    -    print(MSERidgePredict[i])
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')
    -
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    The results here agree when we force Scikit-Learn's Ridge function to include the first column in our design matrix. -We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix. -What happens if we do not include the intercept in our fit? -Let us see how we can change this code by zero centering (thanks to Stian Bilek for inpouts here). +

    We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution. +We define this distribution as

    +$$ +p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}, +$$ + +

    which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \).

    + +

    Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have

    + +$$ +p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}). +$$ + +

    We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is +in case we have a simple one-dimensional input and output case +

    +$$ +\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})]. +$$ + +

    In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \). +We can now rewrite the above probability as +

    +$$ +p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. +$$ + +

    It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \).

    @@ -417,7 +324,7 @@ Let us see how we can change this code by zero centering (thanks to Stian Bilek

  • 45
  • 46
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs037.html b/doc/pub/week36/html/._week36-bs037.html index cfcab41c0..83e029ff0 100644 --- a/doc/pub/week36/html/._week36-bs037.html +++ b/doc/pub/week36/html/._week36-bs037.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,115 +266,31 @@ MathJax.Hub.Config({

     

     

     

    -

    Taking out the mean

    +

    Maximum Likelihood Estimation (MLE)

    - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -from sklearn.preprocessing import StandardScaler
    +

    In statistics, maximum likelihood estimation (MLE) is a method of +estimating the parameters of an assumed probability distribution, +given some observed data. This is achieved by maximizing a likelihood +function so that, under the assumed statistical model, the observed +data is the most probable. +

    -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(315) +

    We will assume here that our events are given by the above Gaussian +distribution and we will determine the optimal parameters \( \beta \) by +maximizing the above PDF. However, computing the derivatives of a +product function is cumbersome and can easily lead to overflow and/or +underflowproblems, with potentials for loss of numerical precision. +

    -n = 100 -x = np.random.rand(n) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) +

    In practice, it is more convenient to maximize the logarithm of the +PDF because it is a monotonically increasing function of the argument. +Alternatively, and this will be our option, we will minimize the +negative of the logarithm since this is a monotonically decreasing +function. +

    -Maxpolydegree = 20 -X = np.zeros((n,Maxpolydegree-1)) - -for degree in range(1,Maxpolydegree): #No intercept column - X[:,degree-1] = x**(degree) - -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) - -#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable -X_train_mean = np.mean(X_train,axis=0) -#Center by removing mean from each feature -X_train_scaled = X_train - X_train_mean -X_test_scaled = X_test - X_train_mean -#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered) -#Remove the intercept from the training data. -y_scaler = np.mean(y_train) -y_train_scaled = y_train - y_scaler - -p = Maxpolydegree-1 -I = np.eye(p,p) -# Decide which values of lambda to use -nlambdas = 6 -MSEOwnRidgePredict = np.zeros(nlambdas) -MSERidgePredict = np.zeros(nlambdas) - -lambdas = np.logspace(-4, 2, nlambdas) -for i in range(nlambdas): - lmb = lambdas[i] - OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled) - intercept_ = y_scaler - X_train_mean@OwnRidgeBeta #The intercept can be shifted so the model can predict on uncentered data - #Add intercept to prediction - ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler - RegRidge = linear_model.Ridge(lmb) - RegRidge.fit(X_train,y_train) - ypredictRidge = RegRidge.predict(X_test) - MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge) - MSERidgePredict[i] = MSE(y_test,ypredictRidge) - print("Beta values for own Ridge implementation") - print(OwnRidgeBeta) #Intercept is given by mean of target variable - print("Beta values for Scikit-Learn Ridge implementation") - print(RegRidge.coef_) - print('Intercept from own implementation:') - print(intercept_) - print('Intercept from Scikit-Learn Ridge implementation') - print(RegRidge.intercept_) - print("MSE values for own Ridge implementation") - print(MSEOwnRidgePredict[i]) - print("MSE values for Scikit-Learn Ridge implementation") - print(MSERidgePredict[i]) - - -# Now plot the results -plt.figure() -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'b--', label = 'MSE own Ridge Test') -plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test') -plt.xlabel('log10(lambda)') -plt.ylabel('MSE') -plt.legend() -plt.show() -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    We see here, when compared to the code which includes explicitely the -intercept column, that our MSE value is actually smaller. This is -because the regularization term does not include the intercept value -\( \beta_0 \) in the fitting. This applies to Lasso regularization as -well. It means that our optimization is now done only with the -centered matrix and/or vector that enter the fitting procedure. Note -also that the problem with the intercept occurs mainly in these type -of polynomial fitting problem. +

    Note also that maximization/minimization of the logarithm of the PDF +is equivalent to the maximization/minimization of the function itself.

    @@ -431,7 +318,7 @@ of polynomial fitting problem.

  • 46
  • 47
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs038.html b/doc/pub/week36/html/._week36-bs038.html index 767fb68fd..49f912169 100644 --- a/doc/pub/week36/html/._week36-bs038.html +++ b/doc/pub/week36/html/._week36-bs038.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,7 +266,31 @@ MathJax.Hub.Config({

     

     

     

    -

    Friday September 9

    +

    A new Cost Function

    + +

    We could now define a new cost function to minimize, namely the negative logarithm of the above PDF

    + +$$ +C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}, +$$ + +

    which becomes

    +$$ +C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}. +$$ + +

    Taking the derivative of the new cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely

    + +$$ +\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0, +$$ + +

    which leads to the well-known OLS equation for the optimal paramters \( \beta \)

    +$$ +\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}! +$$ + +

    Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.

    @@ -322,7 +317,7 @@ MathJax.Hub.Config({

  • 47
  • 48
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs039.html b/doc/pub/week36/html/._week36-bs039.html index f255d2e5a..0b10f5e2c 100644 --- a/doc/pub/week36/html/._week36-bs039.html +++ b/doc/pub/week36/html/._week36-bs039.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -294,50 +265,42 @@ MathJax.Hub.Config({

     

     

     

    - -

    Linking the regression analysis with a statistical interpretation

    + +

    More basic Statistics and Bayes' theorem

    -

    We will now couple the discussions of ordinary least squares, Ridge -and Lasso regression with a statistical interpretation, that is we -move from a linear algebra analysis to a statistical analysis. In -particular, we will focus on what the regularization terms can result -in. We will amongst other things show that the regularization -parameter can reduce considerably the variance of the parameters -\( \beta \). +

    A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry. +Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.

    -

    The -advantage of doing linear regression is that we actually end up with -analytical expressions for several statistical quantities. -Standard least squares and Ridge regression allow us to -derive quantities like the variance and other expectation values in a -rather straightforward way. +

    Assume we have two domains of events \( X=[x_0,x_1,\dots,x_{n-1}] \) and \( Y=[y_0,y_1,\dots,y_{n-1}] \).

    + +

    We define also the likelihood for \( X \) and \( Y \) as \( p(X) \) and \( p(Y) \) respectively. +The likelihood of a specific event \( x_i \) (or \( y_i \)) is then written as \( p(X=x_i) \) or just \( p(x_i)=p_i \).

    -

    It is assumed that \( \varepsilon_i -\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are -independent, i.e.: -

    +
    +
    + $$ -\begin{align*} -\mbox{Cov}(\varepsilon_{i_1}, -\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} -& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. -\end{align*} +p(X \cup Y)= p(X)+p(Y)-p(X \cap Y). +$$ +
    +
    + + +
    +
    + +$$ +p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X), $$ -

    The randomness of \( \varepsilon_i \) implies that -\( \mathbf{y}_i \) is also a random variable. In particular, -\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim -\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a -non-random scalar. To specify the parameters of the distribution of -\( \mathbf{y}_i \) we need to calculate its first two moments. -

    +

    where we read \( p(X\vert Y) \) as the likelihood of obtaining \( X \) given \( Y \).

    +
    +
    -

    Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The -notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the -row number \( i \) and perform a sum over all values \( p \). -

    + +

    If we have independent events then \( p(X,Y)=p(X)p(Y) \).

    @@ -364,7 +327,7 @@ row number \( i \) and perform a sum over all values \( p \).

  • 48
  • 49
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs040.html b/doc/pub/week36/html/._week36-bs040.html index d09b6f9cd..ce3482bef 100644 --- a/doc/pub/week36/html/._week36-bs040.html +++ b/doc/pub/week36/html/._week36-bs040.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,22 +266,17 @@ MathJax.Hub.Config({

     

     

     

    -

    Assumptions made

    +

    Marginal Probability

    -

    The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off) -that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) -which describe our data -

    +

    The marginal probability is defined in terms of only one of the set of variables \( X,Y \). For a discrete probability we have

    +
    +
    + $$ -\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} -$$ - -

    We approximate this function with our model from the solution of the linear regression equations, that is our -function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with -

    -$$ -\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. +p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i). $$ +
    +

    @@ -338,7 +304,7 @@ $$

  • 49
  • 50
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs041.html b/doc/pub/week36/html/._week36-bs041.html index 3a6cf832a..e232eed6e 100644 --- a/doc/pub/week36/html/._week36-bs041.html +++ b/doc/pub/week36/html/._week36-bs041.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,38 +266,18 @@ MathJax.Hub.Config({

     

     

     

    -

    Expectation value and variance

    +

    Conditional Probability

    -

    We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \)

    +

    The conditional probability, if \( p(Y) > 0 \), is

    +
    +
    + $$ -\begin{align*} -\mathbb{E}(y_i) & = -\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i) -\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, -\end{align*} +p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}. $$ +
    +
    -

    while -its variance is -

    -$$ -\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i -- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) - -[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, -\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ & -= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i -\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i, -\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 -\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + -\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 -\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, -\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. -\end{align*} -$$ - -

    Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with -mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD). -

    @@ -352,8 +303,6 @@ mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (n

  • 49
  • 50
  • 51
  • -
  • ...
  • -
  • 59
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs042.html b/doc/pub/week36/html/._week36-bs042.html index 05c78da57..528bbf3d3 100644 --- a/doc/pub/week36/html/._week36-bs042.html +++ b/doc/pub/week36/html/._week36-bs042.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,82 +266,20 @@ MathJax.Hub.Config({

     

     

     

    -

    Expectation value and variance for \( \boldsymbol{\beta} \)

    +

    Bayes' Theorem

    -

    With the OLS expressions for the optimal parameters \( \boldsymbol{\hat{\beta}} \) we can evaluate the expectation value

    +

    If we combine the conditional probability with the marginal probability and the standard product rule, we have

    $$ -\mathbb{E}(\boldsymbol{\hat{\beta}}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. +p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, $$ -

    This means that the estimator of the regression parameters is unbiased.

    - -

    We can also calculate the variance

    - -

    The variance of the optimal value \( \boldsymbol{\hat{\beta}} \) is

    -$$ -\begin{eqnarray*} -\mbox{Var}(\boldsymbol{\hat{\beta}}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \} -\\ -& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \} -\\ -% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} -% \\ -% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} -% \\ -& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} -\\ -& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} -% \\ -% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1} -% \\ -% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T -\\ -& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} -\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}, -\end{eqnarray*} -$$ - -

    where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) = -\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + -\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2 -\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the -variance of the estimate of the \( j \)-th regression coefficient: -\( \boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \). This may be used to -construct a confidence interval for the estimates. -

    - -

    In a similar way, we can obtain analytical expressions for say the -expectation values of the parameters \( \boldsymbol{\beta} \) and their variance -when we employ Ridge regression, allowing us again to define a confidence interval. -

    - -

    It is rather straightforward to show that

    -$$ -\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}. -$$ - -

    We see clearly that -\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased. -

    - -

    We can also compute the variance as

    +

    which we can rewrite as

    $$ -\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}, $$ -

    and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero.

    - -

    With this, we can compute the difference

    - -$$ -\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. -$$ - -

    The difference is non-negative definite since each component of the -matrix product is non-negative definite. -This means the variance we obtain with the standard OLS will always for \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. -

    +

    which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \).

    @@ -395,9 +304,6 @@ This means the variance we obtain with the standard OLS will always for \( \lamb

  • 49
  • 50
  • 51
  • -
  • 52
  • -
  • ...
  • -
  • 59
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs043.html b/doc/pub/week36/html/._week36-bs043.html index 54edcc8fb..5aa9e1d9d 100644 --- a/doc/pub/week36/html/._week36-bs043.html +++ b/doc/pub/week36/html/._week36-bs043.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,27 +266,17 @@ MathJax.Hub.Config({

     

     

     

    -

    Deriving OLS from a probability distribution

    +

    Interpretations of Bayes' Theorem

    -

    Our basic assumption when we derived the OLS equations was to assume -that our output is determined by a given continuous function -\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal -distribution with zero mean value and an undetermined variance -\( \sigma^2 \). +

    The quantity \( p(Y\vert X) \) on the right-hand side of the theorem is +evaluated for the observed data \( Y \) and can be viewed as a function of +the parameter space represented by \( X \). This function is not +necesseraly normalized and is normally called the likelihood function.

    -

    We found above that the outputs \( \boldsymbol{y} \) have a mean value given by -\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to -the design matrix are not stochastic variables, we can assume that the -probability distribution of our targets is also a normal distribution -but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a -single output \( y_i \) is given by the Gaussian distribution -

    - -$$ -y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ +

    The function \( p(X) \) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.

    +

    Let us try to illustrate Bayes' theorem through an example.

    @@ -339,10 +300,6 @@ $$

  • 49
  • 50
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • ...
  • -
  • 59
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs044.html b/doc/pub/week36/html/._week36-bs044.html index 5597ca0bc..6ecddbdb0 100644 --- a/doc/pub/week36/html/._week36-bs044.html +++ b/doc/pub/week36/html/._week36-bs044.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,38 +266,27 @@ MathJax.Hub.Config({

     

     

     

    -

    Independent and Identically Distrubuted (iid)

    +

    Example of Usage of Bayes' theorem

    -

    We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution. -We define this distribution as +

    Let us suppose that you are undergoing a series of mammography scans in +order to rule out possible breast cancer cases. We define the +sensitivity for a positive event by the variable \( X \). It takes binary +values with \( X=1 \) representing a positive event and \( X=0 \) being a +negative event. We reserve \( Y \) as a classification parameter for +either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).

    -$$ -p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}, -$$ -

    which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \).

    +

    We let \( Y=1 \) represent the the case of having breast cancer and \( Y=0 \) as not.

    -

    Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have

    +

    Let us assume that if you have breast cancer, the test will be positive with a probability of \( 0.8 \), that is we have

    $$ -p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}). +p(X=1\vert Y=1) =0.8. $$ -

    We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is -in case we have a simple one-dimensional input and output case +

    This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of \( 80\% \) for having cancer. +It is however not correct, as the following Bayesian analysis shows.

    -$$ -\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})]. -$$ - -

    In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \). -We can now rewrite the above probability as -

    -$$ -p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \).

    @@ -349,11 +309,6 @@ $$

  • 49
  • 50
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • 54
  • -
  • ...
  • -
  • 59
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs045.html b/doc/pub/week36/html/._week36-bs045.html index e8f2b2d4b..215a33b93 100644 --- a/doc/pub/week36/html/._week36-bs045.html +++ b/doc/pub/week36/html/._week36-bs045.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,32 +266,28 @@ MathJax.Hub.Config({

     

     

     

    -

    Maximum Likelihood Estimation (MLE)

    +

    Doing it correctly

    -

    In statistics, maximum likelihood estimation (MLE) is a method of -estimating the parameters of an assumed probability distribution, -given some observed data. This is achieved by maximizing a likelihood -function so that, under the assumed statistical model, the observed -data is the most probable. +

    If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number. +Let us assume that the prior probability in the population as a whole is

    -

    We will assume here that our events are given by the above Gaussian -distribution and we will determine the optimal parameters \( \beta \) by -maximizing the above PDF. However, computing the derivatives of a -product function is cumbersome and can easily lead to overflow and/or -underflowproblems, with potentials for loss of numerical precision. -

    +$$ +p(Y=1) =0.004. +$$ -

    In practice, it is more convenient to maximize the logarithm of the -PDF because it is a monotonically increasing function of the argument. -Alternatively, and this will be our option, we will minimize the -negative of the logarithm since this is a monotonically decreasing -function. -

    +

    We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have

    +$$ +p(X=1\vert Y=0) =0.1. +$$ -

    Note also that maximization/minimization of the logarithm of the PDF -is equivalent to the maximization/minimization of the function itself. -

    +

    Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute

    + +$$ +p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031. +$$ + +

    That is, in case of a positive test, there is only a \( 3\% \) chance of having breast cancer!

    @@ -342,12 +309,6 @@ is equivalent to the maximization/minimization of the function itself.

  • 49
  • 50
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • 54
  • -
  • 55
  • -
  • ...
  • -
  • 59
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs046.html b/doc/pub/week36/html/._week36-bs046.html index 11e698ad0..6e9f15581 100644 --- a/doc/pub/week36/html/._week36-bs046.html +++ b/doc/pub/week36/html/._week36-bs046.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,31 +266,15 @@ MathJax.Hub.Config({

     

     

     

    -

    A new Cost Function

    +

    Bayes' Theorem and Ridge and Lasso Regression

    -

    We could now define a new cost function to minimize, namely the negative logarithm of the above PDF

    +

    Hitherto we have discussed Ridge and Lasso regression in terms of a +linear analysis. This may to many of you feel rather technical and +perhaps not that intuitive. The question is whether we can develop a +more intuitive way of understanding what Ridge and Lasso express. +

    -$$ -C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}, -$$ - -

    which becomes

    -$$ -C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}. -$$ - -

    Taking the derivative of the new cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely

    - -$$ -\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0, -$$ - -

    which leads to the well-known OLS equation for the optimal paramters \( \beta \)

    -$$ -\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}! -$$ - -

    Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.

    +

    Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit.

    @@ -340,13 +295,6 @@ $$

  • 49
  • 50
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • 54
  • -
  • 55
  • -
  • 56
  • -
  • ...
  • -
  • 59
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs047.html b/doc/pub/week36/html/._week36-bs047.html index c91b1e9db..2be30b11b 100644 --- a/doc/pub/week36/html/._week36-bs047.html +++ b/doc/pub/week36/html/._week36-bs047.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,41 +266,103 @@ MathJax.Hub.Config({

     

     

     

    -

    More basic Statistics and Bayes' theorem

    +

    Test Function for what happens with OLS, Ridge and Lasso

    -

    A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry. -Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics. +

    We will play around with a study of the values for the optimal +parameters \( \boldsymbol{\beta} \) using OLS, Ridge and Lasso regression. For +OLS, you will notice as function of the noise and polynomial degree, +that the parameters \( \beta \) will fluctuate from order to order in the +polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.

    -

    Assume we have two domains of events \( X=[x_0,x_1,\dots,x_{n-1}] \) and \( Y=[y_0,y_1,\dots,y_{n-1}] \).

    +

    For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one.

    -

    We define also the likelihood for \( X \) and \( Y \) as \( p(X) \) and \( p(Y) \) respectively. -The likelihood of a specific event \( x_i \) (or \( y_i \)) is then written as \( p(X=x_i) \) or just \( p(x_i)=p_i \). -

    -
    -
    - -$$ -p(X \cup Y)= p(X)+p(Y)-p(X \cap Y). -$$ + +
    +
    +
    +
    +
    +
    import numpy as np
    +import matplotlib.pyplot as plt
    +from sklearn.model_selection import train_test_split
    +from sklearn import linear_model
    +
    +def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +# Make data set.
    +n = 10000
    +x = np.random.rand(n)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    +
    +Maxpolydegree = 5
    +X = np.zeros((len(x),Maxpolydegree))
    +X[:,0] = 1.0
    +
    +for polydegree in range(1, Maxpolydegree):
    +    for degree in range(polydegree):
    +        X[:,degree] = x**(degree)
    +
    +
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +
    +# matrix inversion to find beta
    +OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train
    +print(OLSbeta)
    +ypredictOLS = X_test @ OLSbeta
    +print("Test MSE OLS")
    +print(MSE(y_test,ypredictOLS))
    +# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
    +# Decide which values of lambda to use
    +nlambdas = 4
    +MSERidgePredict = np.zeros(nlambdas)
    +MSELassoPredict = np.zeros(nlambdas)
    +lambdas = np.logspace(-3, 1, nlambdas)
    +for i in range(nlambdas):
    +    lmb = lambdas[i]
    +    # Make the fit using Ridge and Lasso
    +    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    +    RegRidge.fit(X_train,y_train)
    +    RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
    +    RegLasso.fit(X_train,y_train)
    +    # and then make the prediction
    +    ypredictRidge = RegRidge.predict(X_test)
    +    ypredictLasso = RegLasso.predict(X_test)
    +    # Compute the MSE and print it
    +    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    +    MSELassoPredict[i] = MSE(y_test,ypredictLasso)
    +    print(lmb,RegRidge.coef_)
    +    print(lmb,RegLasso.coef_)
    +# Now plot the results
    +plt.figure()
    +plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
    +plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
    +plt.xlabel('log10(lambda)')
    +plt.ylabel('MSE')
    +plt.legend()
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    - -
    -
    - -$$ -p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X), -$$ - -

    where we read \( p(X\vert Y) \) as the likelihood of obtaining \( X \) given \( Y \).

    -
    -
    - - -

    If we have independent events then \( p(X,Y)=p(X)p(Y) \).

    +

    How can we understand this?

    @@ -349,14 +382,6 @@ $$

  • 49
  • 50
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • 54
  • -
  • 55
  • -
  • 56
  • -
  • 57
  • -
  • ...
  • -
  • 59
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs048.html b/doc/pub/week36/html/._week36-bs048.html index d4253959f..4ec032804 100644 --- a/doc/pub/week36/html/._week36-bs048.html +++ b/doc/pub/week36/html/._week36-bs048.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,18 +266,32 @@ MathJax.Hub.Config({

     

     

     

    -

    Marginal Probability

    +

    Invoking Bayes' theorem

    -

    The marginal probability is defined in terms of only one of the set of variables \( X,Y \). For a discrete probability we have

    -
    -
    - -$$ -p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i). -$$ -
    -
    +

    Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression.

    +

    For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case)

    +$$ +\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})], +$$ + +

    is given by

    +$$ +p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. +$$ + +

    In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \( \boldsymbol{\beta} \) given a domain of events \( \boldsymbol{D} \)? That is, how can we define the posterior probability

    + +$$ +p(\boldsymbol{\beta}\vert\boldsymbol{D}). +$$ + +

    Bayes' theorem comes to our rescue here since (omitting the normalization constant)

    +$$ +p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}). +$$ + +

    We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one for the prior \( p(\boldsymbol{\beta} \)!

    @@ -325,15 +310,6 @@ $$

  • 49
  • 50
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • 54
  • -
  • 55
  • -
  • 56
  • -
  • 57
  • -
  • 58
  • -
  • ...
  • -
  • 59
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs049.html b/doc/pub/week36/html/._week36-bs049.html index 66f4abff1..48e0bbf5e 100644 --- a/doc/pub/week36/html/._week36-bs049.html +++ b/doc/pub/week36/html/._week36-bs049.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,18 +266,41 @@ MathJax.Hub.Config({

     

     

     

    -

    Conditional Probability

    +

    Ridge and Bayes

    -

    The conditional probability, if \( p(Y) > 0 \), is

    -
    -
    - -$$ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}. -$$ -
    -
    +

    With the posterior probability defined by a likelihood which we have +already modeled and an unknown prior, we are now ready to make +additional models for the prior. +

    +

    We can, based on our discussions of the variance of \( \boldsymbol{\beta} \) and the mean value, assume that the prior for the values \( \boldsymbol{\beta} \) is given by a Gaussian with mean value zero and variance \( \tau^2 \), that is

    + +$$ +p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. +$$ + +

    Our posterior probability becomes then (omitting the normalization factor which is just a constant)

    +$$ +p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. +$$ + +

    We can now optimize this quantity with respect to \( \boldsymbol{\beta} \). As we +did for OLS, this is most conveniently done by taking the negative +logarithm of the posterior probability. Doing so and leaving out the +constants terms that do not depend on \( \beta \), we have +

    + +$$ +C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2, +$$ + +

    and replacing \( 1/2\tau^2 \) with \( \lambda \) we have

    + +$$ +C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2, +$$ + +

    which is our Ridge cost function! Nice, isn't it?

    @@ -324,14 +318,6 @@ $$

  • 49
  • 50
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • 54
  • -
  • 55
  • -
  • 56
  • -
  • 57
  • -
  • 58
  • -
  • 59
  • »
  • diff --git a/doc/pub/week36/html/._week36-bs050.html b/doc/pub/week36/html/._week36-bs050.html index fd8c055d7..f71264ab0 100644 --- a/doc/pub/week36/html/._week36-bs050.html +++ b/doc/pub/week36/html/._week36-bs050.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -295,20 +266,35 @@ MathJax.Hub.Config({

     

     

     

    -

    Bayes' Theorem

    +

    Lasso and Bayes

    -

    If we combine the conditional probability with the marginal probability and the standard product rule, we have

    -$$ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, -$$ - -

    which we can rewrite as

    +

    To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (Laplace in this case) with zero mean value, that is

    $$ -p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}, +p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. $$ -

    which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \).

    +

    Our posterior probability becomes then (omitting the normalization factor which is just a constant)

    +$$ +p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. +$$ + +

    Taking the negative +logarithm of the posterior probability and leaving out the +constants terms that do not depend on \( \beta \), we have +

    + +$$ +C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1, +$$ + +

    and replacing \( 1/\tau \) with \( \lambda \) we have

    + +$$ +C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1, +$$ + +

    which is our Lasso cost function!

    @@ -325,15 +311,6 @@ $$

  • 49
  • 50
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • 54
  • -
  • 55
  • -
  • 56
  • -
  • 57
  • -
  • 58
  • -
  • 59
  • -
  • »
  • diff --git a/doc/pub/week36/html/week36-bs.html b/doc/pub/week36/html/week36-bs.html index 12be7d203..631b17a9a 100644 --- a/doc/pub/week36/html/week36-bs.html +++ b/doc/pub/week36/html/week36-bs.html @@ -37,6 +37,11 @@ doconce format html week36.do.txt --html_style=bootstrap --pygments_html_style=d @@ -225,65 +206,55 @@ MathJax.Hub.Config({ Contents @@ -313,7 +284,7 @@ MathJax.Hub.Config({
    -

    May 29, 2023

    +

    September 4-8, 2023


    @@ -338,7 +309,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 59
  • +
  • 51
  • »
  • diff --git a/doc/pub/week36/html/week36-reveal.html b/doc/pub/week36/html/week36-reveal.html index 79ad92daf..731533028 100644 --- a/doc/pub/week36/html/week36-reveal.html +++ b/doc/pub/week36/html/week36-reveal.html @@ -184,7 +184,7 @@ MathJax.Hub.Config({
    -

    May 29, 2023

    +

    September 4-8, 2023


    @@ -197,17 +197,25 @@ MathJax.Hub.Config({

    Plans for week 36

    -
      -

    • Summary from last week on discussion of SVD, Ridge and Lasso linear regression.
    • -

    • Linear Regression and links with Statistics, Resampling methods and presentation of first project
    • -
    -

    -

    Recommended Reading:

      -

    1. Lectures on Regression
    2. -

    3. Bishop 1.1, 1.2, 2.1, 2.2, 2.3 and 3.1
    4. -

    5. Hastie et al chapter 3
    6. +

    7. Material for the active learning sessions on Tuesday and Wednesday +
        +

      1. Summary from last week on discussion of SVD, Ridge and Lasso linear regression.
      2. +

      3. Recommended Reading: Hastie et al chapter 3, see https://link.springer.com/book/10.1007/978-0-387-84858-7
      4. +

      5. Presentation and discussion of first project
      +

      +

    8. Material for the lecture on Thursday September 7 +
        +

      1. Linear Regression and links with Statistics, Resampling methods
      2. +

      3. Recommended Reading: Hastie et al chapter 3, see https://link.springer.com/book/10.1007/978-0-387-84858-7
      4. +
      +

      +

    +
    + +
    +

    Material for the active learning sessions Tuesday and Wednesday

    @@ -826,7 +834,7 @@ $$ $$

     
    -

    Plotting these results (figure in handwritten notes for week 36) shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).

    +

    Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).

    @@ -1275,597 +1283,7 @@ plt.show()
    -

    To think about, first part

    - -

    When you are comparing your own code with for example Scikit-Learn's -library, there are some technicalities to keep in mind. The examples -here demonstrate some of these aspects with potential pitfalls. -

    - -

    The discussion here focuses on the role of the intercept, how we can -set up the design matrix, what scaling we should use and other topics -which tend confuse us. -

    - -

    The intercept can be interpreted as the expected value of our -target/output variables when all other predictors are set to zero. -Thus, if we cannot assume that the expected outputs/targets are zero -when all predictors are zero (the columns in the design matrix), it -may be a bad idea to implement a model which penalizes the intercept. -Furthermore, in for example Ridge and Lasso regression, the default solutions -from the library Scikit-Learn (when not shrinking \( \beta_0 \)) for the unknown parameters -\( \boldsymbol{\beta} \), are derived under the assumption that both \( \boldsymbol{y} \) and -\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values. -

    -
    - -
    -

    More thinking

    - -

    If our predictors represent different scales, then it is important to -standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each -column from the corresponding column and dividing the column with its -standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, -the results may differ. -

    - -

    The -Standadscaler -function in Scikit-Learn does this for us. For the data sets we -have been studying in our various examples, the data are in many cases -already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a -survey of your data, with a critical assessment of them in case you need to scale the data. -

    - -

    If you need to scale the data, not doing so will give an unfair -penalization of the parameters since their magnitude depends on the -scale of their corresponding predictor. -

    - -

    Suppose as an example that you -you have an input variable given by the heights of different persons. -Human height might be measured in inches or meters or -kilometers. If measured in kilometers, a standard linear regression -model with this predictor would probably give a much bigger -coefficient term, than if measured in millimeters. -This can clearly lead to problems in evaluating the cost/loss functions. -

    -
    - -
    -

    Still thinking

    - -

    Keep in mind that when you transform your data set before training a model, the same transformation needs to be done -on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows -

    - - - -
    -
    -
    -
    -
    -
    #Model training, we compute the mean value of y and X
    -y_train_mean = np.mean(y_train)
    -X_train_mean = np.mean(X_train,axis=0)
    -X_train = X_train - X_train_mean
    -y_train = y_train - y_train_mean
    -
    -# The we fit our model with the training data
    -trained_model = some_model.fit(X_train,y_train)
    -
    -
    -#Model prediction, we need also to transform our data set used for the prediction.
    -X_test = X_test - X_train_mean #Use mean from training data
    -y_pred = trained_model(X_test)
    -y_pred = y_pred + y_train_mean
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    What does centering (subtracting the mean values) mean mathematically?

    - -

    Let us try to understand what this may imply mathematically when we -subtract the mean values, also known as zero centering. For -simplicity, we will focus on ordinary regression, as done in the above example. -

    - -

    The cost/loss function for regression is

    -

     
    -$$ -C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. -$$ -

     
    - -

    Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.

    - -

    What we have done is to single out the \( \beta_0 \) term in the definition of the mean squared error (MSE). -The design matrix -\( X \) does in this case not contain any intercept column. -When we take the derivative with respect to \( \beta_0 \), we want the derivative to obey -

    -

     
    -$$ -\frac{\partial C}{\partial \beta_j} = 0, -$$ -

     
    - -

    for all \( j \). For \( \beta_0 \) we have

    - -

     
    -$$ -\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). -$$ -

     
    - -

    Multiplying away the constant \( 2/n \), we obtain

    -

     
    -$$ -\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. -$$ -

     
    -

    - -
    -

    Further Manipulations

    - -

    Let us special first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \). -Our result for \( \beta_0 \) simplifies then to -

    -

     
    -$$ -n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. -$$ -

     
    - -

    We obtain then

    -

     
    -$$ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. -$$ -

     
    - -

    If we define

    -

     
    -$$ -\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, -$$ -

     
    - -

    and if we define the mean value of the outputs as

    -

     
    -$$ -\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, -$$ -

     
    - -

    we have

    -

     
    -$$ -\beta_0 = \mu_y - \beta_1\mu_{1}. -$$ -

     
    - -

    In the general case, that is we have more parameters than \( \beta_0 \) and \( \beta_1 \), we have

    -

     
    -$$ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. -$$ -

     
    - -

    Replacing \( y_i \) with \( y_i - y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)

    -

     
    -$$ -C(\boldsymbol{\beta}) = (\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta})^T(\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta}). -$$ -

     
    -

    - -
    -

    Wrapping it up

    - -

    If we minimize with respect to \( \boldsymbol{\beta} \) we have then

    - -

     
    -$$ -\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, -$$ -

     
    - -

    where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \) -and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \). -

    - -

    For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then

    -

     
    -$$ -\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}. -$$ -

     
    - -

    What does this mean? And why do we insist on all this? Let us look at some examples.

    -
    - -
    -

    Linear Regression code, Intercept handling first

    - -

    This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (code example thanks to Øyvind Sigmundson Schøyen). Here our scaling of the data is done by subtracting the mean values only. -Note also that we do not split the data into training and test. -

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import matplotlib.pyplot as plt
    -
    -from sklearn.linear_model import LinearRegression
    -
    -
    -np.random.seed(2021)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -
    -def fit_beta(X, y):
    -    return np.linalg.pinv(X.T @ X) @ X.T @ y
    -
    -
    -true_beta = [2, 0.5, 3.7]
    -
    -x = np.linspace(0, 1, 11)
    -y = np.sum(
    -    np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0
    -) + 0.1 * np.random.normal(size=len(x))
    -
    -degree = 3
    -X = np.zeros((len(x), degree))
    -
    -# Include the intercept in the design matrix
    -for p in range(degree):
    -    X[:, p] = x ** p
    -
    -beta = fit_beta(X, y)
    -
    -# Intercept is included in the design matrix
    -skl = LinearRegression(fit_intercept=False).fit(X, y)
    -
    -print(f"True beta: {true_beta}")
    -print(f"Fitted beta: {beta}")
    -print(f"Sklearn fitted beta: {skl.coef_}")
    -ypredictOwn = X @ beta
    -ypredictSKL = skl.predict(X)
    -print(f"MSE with intercept column")
    -print(MSE(y,ypredictOwn))
    -print(f"MSE with intercept column from SKL")
    -print(MSE(y,ypredictSKL))
    -
    -
    -plt.figure()
    -plt.scatter(x, y, label="Data")
    -plt.plot(x, X @ beta, label="Fit")
    -plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)")
    -
    -
    -# Do not include the intercept in the design matrix
    -X = np.zeros((len(x), degree - 1))
    -
    -for p in range(degree - 1):
    -    X[:, p] = x ** (p + 1)
    -
    -# Intercept is not included in the design matrix
    -skl = LinearRegression(fit_intercept=True).fit(X, y)
    -
    -# Use centered values for X and y when computing coefficients
    -y_offset = np.average(y, axis=0)
    -X_offset = np.average(X, axis=0)
    -
    -beta = fit_beta(X - X_offset, y - y_offset)
    -intercept = np.mean(y_offset - X_offset @ beta)
    -
    -print(f"Manual intercept: {intercept}")
    -print(f"Fitted beta (wiothout intercept): {beta}")
    -print(f"Sklearn intercept: {skl.intercept_}")
    -print(f"Sklearn fitted beta (without intercept): {skl.coef_}")
    -ypredictOwn = X @ beta
    -ypredictSKL = skl.predict(X)
    -print(f"MSE with Manual intercept")
    -print(MSE(y,ypredictOwn+intercept))
    -print(f"MSE with Sklearn intercept")
    -print(MSE(y,ypredictSKL))
    -
    -plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)")
    -plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)")
    -plt.grid()
    -plt.legend()
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    The intercept is the value of our output/target variable -when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case). -

    - -

    Printing the MSE, we see first that both methods give the same MSE, as -they should. However, when we move to for example Ridge regression, -the way we treat the intercept may give a larger or smaller MSE, -meaning that the MSE can be penalized by the value of the -intercept. Not including the intercept in the fit, means that the -regularization term does not include \( \beta_0 \). For different values -of \( \lambda \), this may lead to differeing MSE values. -

    - -

    To remind the reader, the regularization term, with the intercept in Ridge regression is given by

    -

     
    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, -$$ -

     
    - -

    but when we take out the intercept, this equation becomes

    -

     
    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. -$$ -

     
    - -

    For Lasso regression we have

    -

     
    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. -$$ -

     
    - -

    It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get a MSE which then contains the intercept.

    -
    - -
    -

    Code Examples

    - -

    Armed with this wisdom, we attempt first to simply set the intercept equal to False in our implementation of Ridge regression for our well-known vanilla data set.

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(3155)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)
    -
    -Maxpolydegree = 20
    -X = np.zeros((n,Maxpolydegree))
    -#We include explicitely the intercept column
    -for degree in range(Maxpolydegree):
    -    X[:,degree] = x**degree
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -p = Maxpolydegree
    -I = np.eye(p,p)
    -# Decide which values of lambda to use
    -nlambdas = 6
    -MSEOwnRidgePredict = np.zeros(nlambdas)
    -MSERidgePredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
    -    # Note: we include the intercept column and no scaling
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    # and then make the prediction
    -    ytildeOwnRidge = X_train @ OwnRidgeBeta
    -    ypredictOwnRidge = X_test @ OwnRidgeBeta
    -    ytildeRidge = RegRidge.predict(X_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    print("Beta values for own Ridge implementation")
    -    print(OwnRidgeBeta)
    -    print("Beta values for Scikit-Learn Ridge implementation")
    -    print(RegRidge.coef_)
    -    print("MSE values for own Ridge implementation")
    -    print(MSEOwnRidgePredict[i])
    -    print("MSE values for Scikit-Learn Ridge implementation")
    -    print(MSERidgePredict[i])
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')
    -
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    The results here agree when we force Scikit-Learn's Ridge function to include the first column in our design matrix. -We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix. -What happens if we do not include the intercept in our fit? -Let us see how we can change this code by zero centering (thanks to Stian Bilek for inpouts here). -

    -
    - -
    -

    Taking out the mean

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -from sklearn.preprocessing import StandardScaler
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(315)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)
    -
    -Maxpolydegree = 20
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable
    -X_train_mean = np.mean(X_train,axis=0)
    -#Center by removing mean from each feature
    -X_train_scaled = X_train - X_train_mean 
    -X_test_scaled = X_test - X_train_mean
    -#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered)
    -#Remove the intercept from the training data.
    -y_scaler = np.mean(y_train)           
    -y_train_scaled = y_train - y_scaler   
    -
    -p = Maxpolydegree-1
    -I = np.eye(p,p)
    -# Decide which values of lambda to use
    -nlambdas = 6
    -MSEOwnRidgePredict = np.zeros(nlambdas)
    -MSERidgePredict = np.zeros(nlambdas)
    -
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled)
    -    intercept_ = y_scaler - X_train_mean@OwnRidgeBeta #The intercept can be shifted so the model can predict on uncentered data
    -    #Add intercept to prediction
    -    ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler 
    -    RegRidge = linear_model.Ridge(lmb)
    -    RegRidge.fit(X_train,y_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    print("Beta values for own Ridge implementation")
    -    print(OwnRidgeBeta) #Intercept is given by mean of target variable
    -    print("Beta values for Scikit-Learn Ridge implementation")
    -    print(RegRidge.coef_)
    -    print('Intercept from own implementation:')
    -    print(intercept_)
    -    print('Intercept from Scikit-Learn Ridge implementation')
    -    print(RegRidge.intercept_)
    -    print("MSE values for own Ridge implementation")
    -    print(MSEOwnRidgePredict[i])
    -    print("MSE values for Scikit-Learn Ridge implementation")
    -    print(MSERidgePredict[i])
    -
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'b--', label = 'MSE own Ridge Test')
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    We see here, when compared to the code which includes explicitely the -intercept column, that our MSE value is actually smaller. This is -because the regularization term does not include the intercept value -\( \beta_0 \) in the fitting. This applies to Lasso regularization as -well. It means that our optimization is now done only with the -centered matrix and/or vector that enter the fitting procedure. Note -also that the problem with the intercept occurs mainly in these type -of polynomial fitting problem. -

    -
    - -
    -

    Friday September 9

    +

    Material for lecture Thursday September 7

    @@ -2594,155 +2012,6 @@ $$

     

    which is our Lasso cost function!

    - - -

    Exercise 1: mean values and variances in linear regression

    - -

    This exercise deals with various mean values ad variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer).

    - -

    The assumption we have made is -that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) -which describes our data -

    -

     
    -$$ -\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} -$$ -

     
    - -

    We then approximate this function with our model from the solution of the linear regression equations (ordinary least squares OLS), that is our -function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we minimized \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), with -

    -

     
    -$$ -\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. -$$ -

     
    - -

    The matrix \( \boldsymbol{X} \) is the so-called design matrix.

    - - -

    -a) -Show that the expectation value of \( \boldsymbol{y} \) for a given element \( i \) -

    -

     
    -$$ -\begin{align*} -\mathbb{E}(y_i) & =\mathbf{X}_{i, \ast} \, \beta, -\end{align*} -$$ -

     
    - -

    and that -its variance is -

    -

     
    -$$ -\begin{align*} \mbox{Var}(y_i) & = \sigma^2. -\end{align*} -$$ -

     
    - -

    Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with -mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \). -

    - - - - -

    -b) -With the OLS expressions for the parameters \( \boldsymbol{\beta} \) show that -

    -

     
    -$$ -\mathbb{E}(\boldsymbol{\beta}) = \boldsymbol{\beta}. -$$ -

     
    - - - - - -

    -c) -Show finally that the variance of \( \boldsymbol{\beta} \) is -

    -

     
    -$$ -\begin{eqnarray*} -\mbox{Var}(\boldsymbol{\beta}) & = & \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}. -\end{eqnarray*} -$$ -

     
    - - - - - - - -

    Exercise 2: Adding Ridge and Lasso Regression

    - -

    This exercise is a continuation of the exercises from week 35.

    - -

    We will -use the same function to generate our data set, still staying with a -simple function \( y(x) \) which we want to fit using linear regression, -but now extending the analysis to include the Ridge and the Lasso -regression methods. -

    - -

    We will thus again generate our own dataset for a function \( y(x) \) where -\( x \in [0,1] \) and defined by random numbers computed with the uniform -distribution. The function \( y \) is a quadratic polynomial in \( x \) with -added stochastic noise according to the normal distribution \( \cal{N}(0,1) \). -

    - -

    The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).

    - - -
    -
    -
    -
    -
    -
    x = np.random.rand(100)
    -y = 2.0+5*x*x+0.1*np.random.randn(100)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    -a) -Write your own code for the Ridge method (see chapter 3.4 of Hastie et al., equations (3.43) and (3.44)) and compute the parametrization for different values of \( \lambda \). Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \). -

    - - - - -

    -b) -Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parameterizing our function with a second-order polynomial). We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function or using Scikit-Learn to find the parameters \( \beta \). From your results calculate the variance of these parameters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)). Discuss the results of these variances as functions of \( \lambda \). In particular, try to link your discussion with the discussion in Hastie et al. and their figures 3.10 and 3.11. Scikit-Learn may not provide the variance of the parameters \( \beta \). This needs to be checked. With your own code you can however do so. -

    - - - -
    diff --git a/doc/pub/week36/html/week36-solarized.html b/doc/pub/week36/html/week36-solarized.html index ac9235d19..fac9f31f1 100644 --- a/doc/pub/week36/html/week36-solarized.html +++ b/doc/pub/week36/html/week36-solarized.html @@ -64,6 +64,11 @@ div.toc p,a { @@ -254,23 +235,29 @@ MathJax.Hub.Config({
    -

    May 29, 2023

    +

    September 4-8, 2023












    Plans for week 36

    -
      -
    • Summary from last week on discussion of SVD, Ridge and Lasso linear regression.
    • -
    • Linear Regression and links with Statistics, Resampling methods and presentation of first project
    • -
    -

    Recommended Reading:

      -
    1. Lectures on Regression
    2. -
    3. Bishop 1.1, 1.2, 2.1, 2.2, 2.3 and 3.1
    4. -
    5. Hastie et al chapter 3
    6. +
    7. Material for the active learning sessions on Tuesday and Wednesday +
        +
      1. Summary from last week on discussion of SVD, Ridge and Lasso linear regression.
      2. +
      3. Recommended Reading: Hastie et al chapter 3, see https://link.springer.com/book/10.1007/978-0-387-84858-7
      4. +
      5. Presentation and discussion of first project
      +
    8. Material for the lecture on Thursday September 7 +
        +
      1. Linear Regression and links with Statistics, Resampling methods
      2. +
      3. Recommended Reading: Hastie et al chapter 3, see https://link.springer.com/book/10.1007/978-0-387-84858-7
      4. +
      +
    +









    +

    Material for the active learning sessions Tuesday and Wednesday

    +









    Summary from last Week and discussion of SVD, Ridge and Lasso regression with examples

    @@ -794,7 +781,7 @@ $$ 0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\. $$ -

    Plotting these results (figure in handwritten notes for week 36) shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).

    +

    Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).











    Yet another Example

    @@ -1200,559 +1187,7 @@ plt.show()









    -

    To think about, first part

    - -

    When you are comparing your own code with for example Scikit-Learn's -library, there are some technicalities to keep in mind. The examples -here demonstrate some of these aspects with potential pitfalls. -

    - -

    The discussion here focuses on the role of the intercept, how we can -set up the design matrix, what scaling we should use and other topics -which tend confuse us. -

    - -

    The intercept can be interpreted as the expected value of our -target/output variables when all other predictors are set to zero. -Thus, if we cannot assume that the expected outputs/targets are zero -when all predictors are zero (the columns in the design matrix), it -may be a bad idea to implement a model which penalizes the intercept. -Furthermore, in for example Ridge and Lasso regression, the default solutions -from the library Scikit-Learn (when not shrinking \( \beta_0 \)) for the unknown parameters -\( \boldsymbol{\beta} \), are derived under the assumption that both \( \boldsymbol{y} \) and -\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values. -

    - -









    -

    More thinking

    - -

    If our predictors represent different scales, then it is important to -standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each -column from the corresponding column and dividing the column with its -standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, -the results may differ. -

    - -

    The -Standadscaler -function in Scikit-Learn does this for us. For the data sets we -have been studying in our various examples, the data are in many cases -already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a -survey of your data, with a critical assessment of them in case you need to scale the data. -

    - -

    If you need to scale the data, not doing so will give an unfair -penalization of the parameters since their magnitude depends on the -scale of their corresponding predictor. -

    - -

    Suppose as an example that you -you have an input variable given by the heights of different persons. -Human height might be measured in inches or meters or -kilometers. If measured in kilometers, a standard linear regression -model with this predictor would probably give a much bigger -coefficient term, than if measured in millimeters. -This can clearly lead to problems in evaluating the cost/loss functions. -

    - -









    -

    Still thinking

    - -

    Keep in mind that when you transform your data set before training a model, the same transformation needs to be done -on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows -

    - - - -
    -
    -
    -
    -
    -
    #Model training, we compute the mean value of y and X
    -y_train_mean = np.mean(y_train)
    -X_train_mean = np.mean(X_train,axis=0)
    -X_train = X_train - X_train_mean
    -y_train = y_train - y_train_mean
    -
    -# The we fit our model with the training data
    -trained_model = some_model.fit(X_train,y_train)
    -
    -
    -#Model prediction, we need also to transform our data set used for the prediction.
    -X_test = X_test - X_train_mean #Use mean from training data
    -y_pred = trained_model(X_test)
    -y_pred = y_pred + y_train_mean
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    What does centering (subtracting the mean values) mean mathematically?

    - -

    Let us try to understand what this may imply mathematically when we -subtract the mean values, also known as zero centering. For -simplicity, we will focus on ordinary regression, as done in the above example. -

    - -

    The cost/loss function for regression is

    -$$ -C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. -$$ - -

    Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.

    - -

    What we have done is to single out the \( \beta_0 \) term in the definition of the mean squared error (MSE). -The design matrix -\( X \) does in this case not contain any intercept column. -When we take the derivative with respect to \( \beta_0 \), we want the derivative to obey -

    -$$ -\frac{\partial C}{\partial \beta_j} = 0, -$$ - -

    for all \( j \). For \( \beta_0 \) we have

    - -$$ -\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). -$$ - -

    Multiplying away the constant \( 2/n \), we obtain

    -$$ -\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. -$$ - - -









    -

    Further Manipulations

    - -

    Let us special first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \). -Our result for \( \beta_0 \) simplifies then to -

    -$$ -n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. -$$ - -

    We obtain then

    -$$ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. -$$ - -

    If we define

    -$$ -\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, -$$ - -

    and if we define the mean value of the outputs as

    -$$ -\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, -$$ - -

    we have

    -$$ -\beta_0 = \mu_y - \beta_1\mu_{1}. -$$ - -

    In the general case, that is we have more parameters than \( \beta_0 \) and \( \beta_1 \), we have

    -$$ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. -$$ - -

    Replacing \( y_i \) with \( y_i - y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)

    -$$ -C(\boldsymbol{\beta}) = (\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta})^T(\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta}). -$$ - - -









    -

    Wrapping it up

    - -

    If we minimize with respect to \( \boldsymbol{\beta} \) we have then

    - -$$ -\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, -$$ - -

    where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \) -and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \). -

    - -

    For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then

    -$$ -\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}. -$$ - -

    What does this mean? And why do we insist on all this? Let us look at some examples.

    - -









    -

    Linear Regression code, Intercept handling first

    - -

    This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (code example thanks to Øyvind Sigmundson Schøyen). Here our scaling of the data is done by subtracting the mean values only. -Note also that we do not split the data into training and test. -

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import matplotlib.pyplot as plt
    -
    -from sklearn.linear_model import LinearRegression
    -
    -
    -np.random.seed(2021)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -
    -def fit_beta(X, y):
    -    return np.linalg.pinv(X.T @ X) @ X.T @ y
    -
    -
    -true_beta = [2, 0.5, 3.7]
    -
    -x = np.linspace(0, 1, 11)
    -y = np.sum(
    -    np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0
    -) + 0.1 * np.random.normal(size=len(x))
    -
    -degree = 3
    -X = np.zeros((len(x), degree))
    -
    -# Include the intercept in the design matrix
    -for p in range(degree):
    -    X[:, p] = x ** p
    -
    -beta = fit_beta(X, y)
    -
    -# Intercept is included in the design matrix
    -skl = LinearRegression(fit_intercept=False).fit(X, y)
    -
    -print(f"True beta: {true_beta}")
    -print(f"Fitted beta: {beta}")
    -print(f"Sklearn fitted beta: {skl.coef_}")
    -ypredictOwn = X @ beta
    -ypredictSKL = skl.predict(X)
    -print(f"MSE with intercept column")
    -print(MSE(y,ypredictOwn))
    -print(f"MSE with intercept column from SKL")
    -print(MSE(y,ypredictSKL))
    -
    -
    -plt.figure()
    -plt.scatter(x, y, label="Data")
    -plt.plot(x, X @ beta, label="Fit")
    -plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)")
    -
    -
    -# Do not include the intercept in the design matrix
    -X = np.zeros((len(x), degree - 1))
    -
    -for p in range(degree - 1):
    -    X[:, p] = x ** (p + 1)
    -
    -# Intercept is not included in the design matrix
    -skl = LinearRegression(fit_intercept=True).fit(X, y)
    -
    -# Use centered values for X and y when computing coefficients
    -y_offset = np.average(y, axis=0)
    -X_offset = np.average(X, axis=0)
    -
    -beta = fit_beta(X - X_offset, y - y_offset)
    -intercept = np.mean(y_offset - X_offset @ beta)
    -
    -print(f"Manual intercept: {intercept}")
    -print(f"Fitted beta (wiothout intercept): {beta}")
    -print(f"Sklearn intercept: {skl.intercept_}")
    -print(f"Sklearn fitted beta (without intercept): {skl.coef_}")
    -ypredictOwn = X @ beta
    -ypredictSKL = skl.predict(X)
    -print(f"MSE with Manual intercept")
    -print(MSE(y,ypredictOwn+intercept))
    -print(f"MSE with Sklearn intercept")
    -print(MSE(y,ypredictSKL))
    -
    -plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)")
    -plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)")
    -plt.grid()
    -plt.legend()
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    The intercept is the value of our output/target variable -when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case). -

    - -

    Printing the MSE, we see first that both methods give the same MSE, as -they should. However, when we move to for example Ridge regression, -the way we treat the intercept may give a larger or smaller MSE, -meaning that the MSE can be penalized by the value of the -intercept. Not including the intercept in the fit, means that the -regularization term does not include \( \beta_0 \). For different values -of \( \lambda \), this may lead to differeing MSE values. -

    - -

    To remind the reader, the regularization term, with the intercept in Ridge regression is given by

    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, -$$ - -

    but when we take out the intercept, this equation becomes

    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. -$$ - -

    For Lasso regression we have

    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. -$$ - -

    It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get a MSE which then contains the intercept.

    - -









    -

    Code Examples

    - -

    Armed with this wisdom, we attempt first to simply set the intercept equal to False in our implementation of Ridge regression for our well-known vanilla data set.

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(3155)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)
    -
    -Maxpolydegree = 20
    -X = np.zeros((n,Maxpolydegree))
    -#We include explicitely the intercept column
    -for degree in range(Maxpolydegree):
    -    X[:,degree] = x**degree
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -p = Maxpolydegree
    -I = np.eye(p,p)
    -# Decide which values of lambda to use
    -nlambdas = 6
    -MSEOwnRidgePredict = np.zeros(nlambdas)
    -MSERidgePredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
    -    # Note: we include the intercept column and no scaling
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    # and then make the prediction
    -    ytildeOwnRidge = X_train @ OwnRidgeBeta
    -    ypredictOwnRidge = X_test @ OwnRidgeBeta
    -    ytildeRidge = RegRidge.predict(X_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    print("Beta values for own Ridge implementation")
    -    print(OwnRidgeBeta)
    -    print("Beta values for Scikit-Learn Ridge implementation")
    -    print(RegRidge.coef_)
    -    print("MSE values for own Ridge implementation")
    -    print(MSEOwnRidgePredict[i])
    -    print("MSE values for Scikit-Learn Ridge implementation")
    -    print(MSERidgePredict[i])
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')
    -
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    The results here agree when we force Scikit-Learn's Ridge function to include the first column in our design matrix. -We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix. -What happens if we do not include the intercept in our fit? -Let us see how we can change this code by zero centering (thanks to Stian Bilek for inpouts here). -

    - -









    -

    Taking out the mean

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -from sklearn.preprocessing import StandardScaler
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(315)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)
    -
    -Maxpolydegree = 20
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable
    -X_train_mean = np.mean(X_train,axis=0)
    -#Center by removing mean from each feature
    -X_train_scaled = X_train - X_train_mean 
    -X_test_scaled = X_test - X_train_mean
    -#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered)
    -#Remove the intercept from the training data.
    -y_scaler = np.mean(y_train)           
    -y_train_scaled = y_train - y_scaler   
    -
    -p = Maxpolydegree-1
    -I = np.eye(p,p)
    -# Decide which values of lambda to use
    -nlambdas = 6
    -MSEOwnRidgePredict = np.zeros(nlambdas)
    -MSERidgePredict = np.zeros(nlambdas)
    -
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled)
    -    intercept_ = y_scaler - X_train_mean@OwnRidgeBeta #The intercept can be shifted so the model can predict on uncentered data
    -    #Add intercept to prediction
    -    ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler 
    -    RegRidge = linear_model.Ridge(lmb)
    -    RegRidge.fit(X_train,y_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    print("Beta values for own Ridge implementation")
    -    print(OwnRidgeBeta) #Intercept is given by mean of target variable
    -    print("Beta values for Scikit-Learn Ridge implementation")
    -    print(RegRidge.coef_)
    -    print('Intercept from own implementation:')
    -    print(intercept_)
    -    print('Intercept from Scikit-Learn Ridge implementation')
    -    print(RegRidge.intercept_)
    -    print("MSE values for own Ridge implementation")
    -    print(MSEOwnRidgePredict[i])
    -    print("MSE values for Scikit-Learn Ridge implementation")
    -    print(MSERidgePredict[i])
    -
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'b--', label = 'MSE own Ridge Test')
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    We see here, when compared to the code which includes explicitely the -intercept column, that our MSE value is actually smaller. This is -because the regularization term does not include the intercept value -\( \beta_0 \) in the fitting. This applies to Lasso regularization as -well. It means that our optimization is now done only with the -centered matrix and/or vector that enter the fitting procedure. Note -also that the problem with the intercept occurs mainly in these type -of polynomial fitting problem. -

    - -









    -

    Friday September 9

    +

    Material for lecture Thursday September 7

    Linking the regression analysis with a statistical interpretation

    @@ -2385,142 +1820,6 @@ $$

    which is our Lasso cost function!

    - -

    Exercise 1: mean values and variances in linear regression

    - -

    This exercise deals with various mean values ad variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer).

    - -

    The assumption we have made is -that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) -which describes our data -

    -$$ -\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} -$$ - -

    We then approximate this function with our model from the solution of the linear regression equations (ordinary least squares OLS), that is our -function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we minimized \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), with -

    -$$ -\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. -$$ - -

    The matrix \( \boldsymbol{X} \) is the so-called design matrix.

    - - -

    -a) -Show that the expectation value of \( \boldsymbol{y} \) for a given element \( i \) -

    -$$ -\begin{align*} -\mathbb{E}(y_i) & =\mathbf{X}_{i, \ast} \, \beta, -\end{align*} -$$ - -

    and that -its variance is -

    -$$ -\begin{align*} \mbox{Var}(y_i) & = \sigma^2. -\end{align*} -$$ - -

    Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with -mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \). -

    - - - - -

    -b) -With the OLS expressions for the parameters \( \boldsymbol{\beta} \) show that -

    -$$ -\mathbb{E}(\boldsymbol{\beta}) = \boldsymbol{\beta}. -$$ - - - - - -

    -c) -Show finally that the variance of \( \boldsymbol{\beta} \) is -

    -$$ -\begin{eqnarray*} -\mbox{Var}(\boldsymbol{\beta}) & = & \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}. -\end{eqnarray*} -$$ - - - - - - - -

    Exercise 2: Adding Ridge and Lasso Regression

    - -

    This exercise is a continuation of the exercises from week 35.

    - -

    We will -use the same function to generate our data set, still staying with a -simple function \( y(x) \) which we want to fit using linear regression, -but now extending the analysis to include the Ridge and the Lasso -regression methods. -

    - -

    We will thus again generate our own dataset for a function \( y(x) \) where -\( x \in [0,1] \) and defined by random numbers computed with the uniform -distribution. The function \( y \) is a quadratic polynomial in \( x \) with -added stochastic noise according to the normal distribution \( \cal{N}(0,1) \). -

    - -

    The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).

    - - -
    -
    -
    -
    -
    -
    x = np.random.rand(100)
    -y = 2.0+5*x*x+0.1*np.random.randn(100)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    -a) -Write your own code for the Ridge method (see chapter 3.4 of Hastie et al., equations (3.43) and (3.44)) and compute the parametrization for different values of \( \lambda \). Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \). -

    - - - - -

    -b) -Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parameterizing our function with a second-order polynomial). We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function or using Scikit-Learn to find the parameters \( \beta \). From your results calculate the variance of these parameters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)). Discuss the results of these variances as functions of \( \lambda \). In particular, try to link your discussion with the discussion in Hastie et al. and their figures 3.10 and 3.11. Scikit-Learn may not provide the variance of the parameters \( \beta \). This needs to be checked. With your own code you can however do so. -

    - - - -
    © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license diff --git a/doc/pub/week36/html/week36.html b/doc/pub/week36/html/week36.html index dd2e0cc28..75e5e3c1c 100644 --- a/doc/pub/week36/html/week36.html +++ b/doc/pub/week36/html/week36.html @@ -141,6 +141,11 @@ div.toc p,a { @@ -331,23 +312,29 @@ MathJax.Hub.Config({

    -

    May 29, 2023

    +

    September 4-8, 2023












    Plans for week 36

    -
      -
    • Summary from last week on discussion of SVD, Ridge and Lasso linear regression.
    • -
    • Linear Regression and links with Statistics, Resampling methods and presentation of first project
    • -
    -

    Recommended Reading:

      -
    1. Lectures on Regression
    2. -
    3. Bishop 1.1, 1.2, 2.1, 2.2, 2.3 and 3.1
    4. -
    5. Hastie et al chapter 3
    6. +
    7. Material for the active learning sessions on Tuesday and Wednesday +
        +
      1. Summary from last week on discussion of SVD, Ridge and Lasso linear regression.
      2. +
      3. Recommended Reading: Hastie et al chapter 3, see https://link.springer.com/book/10.1007/978-0-387-84858-7
      4. +
      5. Presentation and discussion of first project
      +
    8. Material for the lecture on Thursday September 7 +
        +
      1. Linear Regression and links with Statistics, Resampling methods
      2. +
      3. Recommended Reading: Hastie et al chapter 3, see https://link.springer.com/book/10.1007/978-0-387-84858-7
      4. +
      +
    +









    +

    Material for the active learning sessions Tuesday and Wednesday

    +









    Summary from last Week and discussion of SVD, Ridge and Lasso regression with examples

    @@ -871,7 +858,7 @@ $$ 0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\. $$ -

    Plotting these results (figure in handwritten notes for week 36) shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).

    +

    Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).











    Yet another Example

    @@ -1277,559 +1264,7 @@ plt.show()









    -

    To think about, first part

    - -

    When you are comparing your own code with for example Scikit-Learn's -library, there are some technicalities to keep in mind. The examples -here demonstrate some of these aspects with potential pitfalls. -

    - -

    The discussion here focuses on the role of the intercept, how we can -set up the design matrix, what scaling we should use and other topics -which tend confuse us. -

    - -

    The intercept can be interpreted as the expected value of our -target/output variables when all other predictors are set to zero. -Thus, if we cannot assume that the expected outputs/targets are zero -when all predictors are zero (the columns in the design matrix), it -may be a bad idea to implement a model which penalizes the intercept. -Furthermore, in for example Ridge and Lasso regression, the default solutions -from the library Scikit-Learn (when not shrinking \( \beta_0 \)) for the unknown parameters -\( \boldsymbol{\beta} \), are derived under the assumption that both \( \boldsymbol{y} \) and -\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values. -

    - -









    -

    More thinking

    - -

    If our predictors represent different scales, then it is important to -standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each -column from the corresponding column and dividing the column with its -standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, -the results may differ. -

    - -

    The -Standadscaler -function in Scikit-Learn does this for us. For the data sets we -have been studying in our various examples, the data are in many cases -already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a -survey of your data, with a critical assessment of them in case you need to scale the data. -

    - -

    If you need to scale the data, not doing so will give an unfair -penalization of the parameters since their magnitude depends on the -scale of their corresponding predictor. -

    - -

    Suppose as an example that you -you have an input variable given by the heights of different persons. -Human height might be measured in inches or meters or -kilometers. If measured in kilometers, a standard linear regression -model with this predictor would probably give a much bigger -coefficient term, than if measured in millimeters. -This can clearly lead to problems in evaluating the cost/loss functions. -

    - -









    -

    Still thinking

    - -

    Keep in mind that when you transform your data set before training a model, the same transformation needs to be done -on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows -

    - - - -
    -
    -
    -
    -
    -
    #Model training, we compute the mean value of y and X
    -y_train_mean = np.mean(y_train)
    -X_train_mean = np.mean(X_train,axis=0)
    -X_train = X_train - X_train_mean
    -y_train = y_train - y_train_mean
    -
    -# The we fit our model with the training data
    -trained_model = some_model.fit(X_train,y_train)
    -
    -
    -#Model prediction, we need also to transform our data set used for the prediction.
    -X_test = X_test - X_train_mean #Use mean from training data
    -y_pred = trained_model(X_test)
    -y_pred = y_pred + y_train_mean
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    What does centering (subtracting the mean values) mean mathematically?

    - -

    Let us try to understand what this may imply mathematically when we -subtract the mean values, also known as zero centering. For -simplicity, we will focus on ordinary regression, as done in the above example. -

    - -

    The cost/loss function for regression is

    -$$ -C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. -$$ - -

    Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.

    - -

    What we have done is to single out the \( \beta_0 \) term in the definition of the mean squared error (MSE). -The design matrix -\( X \) does in this case not contain any intercept column. -When we take the derivative with respect to \( \beta_0 \), we want the derivative to obey -

    -$$ -\frac{\partial C}{\partial \beta_j} = 0, -$$ - -

    for all \( j \). For \( \beta_0 \) we have

    - -$$ -\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). -$$ - -

    Multiplying away the constant \( 2/n \), we obtain

    -$$ -\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. -$$ - - -









    -

    Further Manipulations

    - -

    Let us special first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \). -Our result for \( \beta_0 \) simplifies then to -

    -$$ -n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. -$$ - -

    We obtain then

    -$$ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. -$$ - -

    If we define

    -$$ -\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, -$$ - -

    and if we define the mean value of the outputs as

    -$$ -\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, -$$ - -

    we have

    -$$ -\beta_0 = \mu_y - \beta_1\mu_{1}. -$$ - -

    In the general case, that is we have more parameters than \( \beta_0 \) and \( \beta_1 \), we have

    -$$ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. -$$ - -

    Replacing \( y_i \) with \( y_i - y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)

    -$$ -C(\boldsymbol{\beta}) = (\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta})^T(\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta}). -$$ - - -









    -

    Wrapping it up

    - -

    If we minimize with respect to \( \boldsymbol{\beta} \) we have then

    - -$$ -\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, -$$ - -

    where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \) -and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \). -

    - -

    For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then

    -$$ -\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}. -$$ - -

    What does this mean? And why do we insist on all this? Let us look at some examples.

    - -









    -

    Linear Regression code, Intercept handling first

    - -

    This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (code example thanks to Øyvind Sigmundson Schøyen). Here our scaling of the data is done by subtracting the mean values only. -Note also that we do not split the data into training and test. -

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import matplotlib.pyplot as plt
    -
    -from sklearn.linear_model import LinearRegression
    -
    -
    -np.random.seed(2021)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -
    -def fit_beta(X, y):
    -    return np.linalg.pinv(X.T @ X) @ X.T @ y
    -
    -
    -true_beta = [2, 0.5, 3.7]
    -
    -x = np.linspace(0, 1, 11)
    -y = np.sum(
    -    np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0
    -) + 0.1 * np.random.normal(size=len(x))
    -
    -degree = 3
    -X = np.zeros((len(x), degree))
    -
    -# Include the intercept in the design matrix
    -for p in range(degree):
    -    X[:, p] = x ** p
    -
    -beta = fit_beta(X, y)
    -
    -# Intercept is included in the design matrix
    -skl = LinearRegression(fit_intercept=False).fit(X, y)
    -
    -print(f"True beta: {true_beta}")
    -print(f"Fitted beta: {beta}")
    -print(f"Sklearn fitted beta: {skl.coef_}")
    -ypredictOwn = X @ beta
    -ypredictSKL = skl.predict(X)
    -print(f"MSE with intercept column")
    -print(MSE(y,ypredictOwn))
    -print(f"MSE with intercept column from SKL")
    -print(MSE(y,ypredictSKL))
    -
    -
    -plt.figure()
    -plt.scatter(x, y, label="Data")
    -plt.plot(x, X @ beta, label="Fit")
    -plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)")
    -
    -
    -# Do not include the intercept in the design matrix
    -X = np.zeros((len(x), degree - 1))
    -
    -for p in range(degree - 1):
    -    X[:, p] = x ** (p + 1)
    -
    -# Intercept is not included in the design matrix
    -skl = LinearRegression(fit_intercept=True).fit(X, y)
    -
    -# Use centered values for X and y when computing coefficients
    -y_offset = np.average(y, axis=0)
    -X_offset = np.average(X, axis=0)
    -
    -beta = fit_beta(X - X_offset, y - y_offset)
    -intercept = np.mean(y_offset - X_offset @ beta)
    -
    -print(f"Manual intercept: {intercept}")
    -print(f"Fitted beta (wiothout intercept): {beta}")
    -print(f"Sklearn intercept: {skl.intercept_}")
    -print(f"Sklearn fitted beta (without intercept): {skl.coef_}")
    -ypredictOwn = X @ beta
    -ypredictSKL = skl.predict(X)
    -print(f"MSE with Manual intercept")
    -print(MSE(y,ypredictOwn+intercept))
    -print(f"MSE with Sklearn intercept")
    -print(MSE(y,ypredictSKL))
    -
    -plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)")
    -plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)")
    -plt.grid()
    -plt.legend()
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    The intercept is the value of our output/target variable -when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case). -

    - -

    Printing the MSE, we see first that both methods give the same MSE, as -they should. However, when we move to for example Ridge regression, -the way we treat the intercept may give a larger or smaller MSE, -meaning that the MSE can be penalized by the value of the -intercept. Not including the intercept in the fit, means that the -regularization term does not include \( \beta_0 \). For different values -of \( \lambda \), this may lead to differeing MSE values. -

    - -

    To remind the reader, the regularization term, with the intercept in Ridge regression is given by

    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, -$$ - -

    but when we take out the intercept, this equation becomes

    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. -$$ - -

    For Lasso regression we have

    -$$ -\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. -$$ - -

    It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get a MSE which then contains the intercept.

    - -









    -

    Code Examples

    - -

    Armed with this wisdom, we attempt first to simply set the intercept equal to False in our implementation of Ridge regression for our well-known vanilla data set.

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(3155)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)
    -
    -Maxpolydegree = 20
    -X = np.zeros((n,Maxpolydegree))
    -#We include explicitely the intercept column
    -for degree in range(Maxpolydegree):
    -    X[:,degree] = x**degree
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -p = Maxpolydegree
    -I = np.eye(p,p)
    -# Decide which values of lambda to use
    -nlambdas = 6
    -MSEOwnRidgePredict = np.zeros(nlambdas)
    -MSERidgePredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
    -    # Note: we include the intercept column and no scaling
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    # and then make the prediction
    -    ytildeOwnRidge = X_train @ OwnRidgeBeta
    -    ypredictOwnRidge = X_test @ OwnRidgeBeta
    -    ytildeRidge = RegRidge.predict(X_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    print("Beta values for own Ridge implementation")
    -    print(OwnRidgeBeta)
    -    print("Beta values for Scikit-Learn Ridge implementation")
    -    print(RegRidge.coef_)
    -    print("MSE values for own Ridge implementation")
    -    print(MSEOwnRidgePredict[i])
    -    print("MSE values for Scikit-Learn Ridge implementation")
    -    print(MSERidgePredict[i])
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')
    -
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    The results here agree when we force Scikit-Learn's Ridge function to include the first column in our design matrix. -We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix. -What happens if we do not include the intercept in our fit? -Let us see how we can change this code by zero centering (thanks to Stian Bilek for inpouts here). -

    - -









    -

    Taking out the mean

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -from sklearn.preprocessing import StandardScaler
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(315)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)
    -
    -Maxpolydegree = 20
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable
    -X_train_mean = np.mean(X_train,axis=0)
    -#Center by removing mean from each feature
    -X_train_scaled = X_train - X_train_mean 
    -X_test_scaled = X_test - X_train_mean
    -#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered)
    -#Remove the intercept from the training data.
    -y_scaler = np.mean(y_train)           
    -y_train_scaled = y_train - y_scaler   
    -
    -p = Maxpolydegree-1
    -I = np.eye(p,p)
    -# Decide which values of lambda to use
    -nlambdas = 6
    -MSEOwnRidgePredict = np.zeros(nlambdas)
    -MSERidgePredict = np.zeros(nlambdas)
    -
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled)
    -    intercept_ = y_scaler - X_train_mean@OwnRidgeBeta #The intercept can be shifted so the model can predict on uncentered data
    -    #Add intercept to prediction
    -    ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler 
    -    RegRidge = linear_model.Ridge(lmb)
    -    RegRidge.fit(X_train,y_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    print("Beta values for own Ridge implementation")
    -    print(OwnRidgeBeta) #Intercept is given by mean of target variable
    -    print("Beta values for Scikit-Learn Ridge implementation")
    -    print(RegRidge.coef_)
    -    print('Intercept from own implementation:')
    -    print(intercept_)
    -    print('Intercept from Scikit-Learn Ridge implementation')
    -    print(RegRidge.intercept_)
    -    print("MSE values for own Ridge implementation")
    -    print(MSEOwnRidgePredict[i])
    -    print("MSE values for Scikit-Learn Ridge implementation")
    -    print(MSERidgePredict[i])
    -
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'b--', label = 'MSE own Ridge Test')
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    We see here, when compared to the code which includes explicitely the -intercept column, that our MSE value is actually smaller. This is -because the regularization term does not include the intercept value -\( \beta_0 \) in the fitting. This applies to Lasso regularization as -well. It means that our optimization is now done only with the -centered matrix and/or vector that enter the fitting procedure. Note -also that the problem with the intercept occurs mainly in these type -of polynomial fitting problem. -

    - -









    -

    Friday September 9

    +

    Material for lecture Thursday September 7

    Linking the regression analysis with a statistical interpretation

    @@ -2462,142 +1897,6 @@ $$

    which is our Lasso cost function!

    - -

    Exercise 1: mean values and variances in linear regression

    - -

    This exercise deals with various mean values ad variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer).

    - -

    The assumption we have made is -that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) -which describes our data -

    -$$ -\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} -$$ - -

    We then approximate this function with our model from the solution of the linear regression equations (ordinary least squares OLS), that is our -function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we minimized \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), with -

    -$$ -\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. -$$ - -

    The matrix \( \boldsymbol{X} \) is the so-called design matrix.

    - - -

    -a) -Show that the expectation value of \( \boldsymbol{y} \) for a given element \( i \) -

    -$$ -\begin{align*} -\mathbb{E}(y_i) & =\mathbf{X}_{i, \ast} \, \beta, -\end{align*} -$$ - -

    and that -its variance is -

    -$$ -\begin{align*} \mbox{Var}(y_i) & = \sigma^2. -\end{align*} -$$ - -

    Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with -mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \). -

    - - - - -

    -b) -With the OLS expressions for the parameters \( \boldsymbol{\beta} \) show that -

    -$$ -\mathbb{E}(\boldsymbol{\beta}) = \boldsymbol{\beta}. -$$ - - - - - -

    -c) -Show finally that the variance of \( \boldsymbol{\beta} \) is -

    -$$ -\begin{eqnarray*} -\mbox{Var}(\boldsymbol{\beta}) & = & \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}. -\end{eqnarray*} -$$ - - - - - - - -

    Exercise 2: Adding Ridge and Lasso Regression

    - -

    This exercise is a continuation of the exercises from week 35.

    - -

    We will -use the same function to generate our data set, still staying with a -simple function \( y(x) \) which we want to fit using linear regression, -but now extending the analysis to include the Ridge and the Lasso -regression methods. -

    - -

    We will thus again generate our own dataset for a function \( y(x) \) where -\( x \in [0,1] \) and defined by random numbers computed with the uniform -distribution. The function \( y \) is a quadratic polynomial in \( x \) with -added stochastic noise according to the normal distribution \( \cal{N}(0,1) \). -

    - -

    The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).

    - - -
    -
    -
    -
    -
    -
    x = np.random.rand(100)
    -y = 2.0+5*x*x+0.1*np.random.randn(100)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    -a) -Write your own code for the Ridge method (see chapter 3.4 of Hastie et al., equations (3.43) and (3.44)) and compute the parametrization for different values of \( \lambda \). Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \). -

    - - - - -

    -b) -Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parameterizing our function with a second-order polynomial). We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function or using Scikit-Learn to find the parameters \( \beta \). From your results calculate the variance of these parameters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)). Discuss the results of these variances as functions of \( \lambda \). In particular, try to link your discussion with the discussion in Hastie et al. and their figures 3.10 and 3.11. Scikit-Learn may not provide the variance of the parameters \( \beta \). This needs to be checked. With your own code you can however do so. -

    - - - -
    © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license diff --git a/doc/pub/week36/ipynb/ipynb-week36-src.tar.gz b/doc/pub/week36/ipynb/ipynb-week36-src.tar.gz index c634bf9f02bc4be5f4a325392269f5a3266e571e..aaf634816ae4a007d594e1f41b5a8146c990ce9b 100644 GIT binary patch literal 192 zcmV;x06+g9iwFP}ar9&W1MSbv3c@f92k@Qu6nTP?*>*b%?%+WX@dY~8xjNU*wnO*! z?gR9sco`z}cli?%LUPE~n_U*Uy9*YBhzX@IW}2`maW&VIIA#!2nlen0t{7lU7$E`R zawolX)^RhO(o|=mtWfXfhOx5zuxEY+p7|$^m9((k_pZ_kly)N5x`vw&HAy1b_9}-$ u3p=*Jh-)W}0IquAMIoKkieJLk=#$}%jly3)<9VLveeD5SuMt212mk;zgj?bO literal 192 zcmV;x06+g9iwFRE26bcr1MSaC4uUWc24L2lVopF>D6lq>1q%~nyg&(qRHVhWM7g~@ z5?yKB5M$DB^H0;sWaf}IBgCkdDLjM5k=V^JKEh^8SBI+n}> zvffHBy|G-6tF-kQr9t_wZ)~fo4|A4N;F*8oSPKLBez3KYAeF^JsRnL{O_T(p8)N~c uLNk4V#%nJ$0+$2uvJ_S*$uEAV)k*W#1pcp&aU92SzV-lRrLW}x2mk=P{8Wno diff --git a/doc/pub/week36/ipynb/week36.ipynb b/doc/pub/week36/ipynb/week36.ipynb index 6be1b27d0..9137437f1 100644 --- a/doc/pub/week36/ipynb/week36.ipynb +++ b/doc/pub/week36/ipynb/week36.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "de098695", + "id": "aa4367c1", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "9d896464", + "id": "e6758e15", "metadata": { "editable": true }, @@ -22,35 +22,46 @@ "# Week 36: Statistical interpretation of Linear Regression and Resampling techniques\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: **May 29, 2023**\n", - "\n", - "Copyright 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" + "Date: **September 4-8, 2023**" ] }, { "cell_type": "markdown", - "id": "2d144eda", + "id": "d223ba4c", "metadata": { "editable": true }, "source": [ "## Plans for week 36\n", "\n", - "* Summary from last week on discussion of SVD, Ridge and Lasso linear regression.\n", + "1. Material for the active learning sessions on Tuesday and Wednesday\n", "\n", - "* Linear Regression and links with Statistics, Resampling methods and presentation of first project\n", + "a. Summary from last week on discussion of SVD, Ridge and Lasso linear regression.\n", "\n", - "Recommended Reading:\n", - "1. Lectures on Regression\n", + "b. Recommended Reading: Hastie et al chapter 3, see \n", "\n", - "2. Bishop 1.1, 1.2, 2.1, 2.2, 2.3 and 3.1\n", + "c. Presentation and discussion of first project\n", "\n", - "3. Hastie et al chapter 3" + "4. Material for the lecture on Thursday September 7\n", + "\n", + "a. Linear Regression and links with Statistics, Resampling methods\n", + "\n", + "b. Recommended Reading: Hastie et al chapter 3, see " ] }, { "cell_type": "markdown", - "id": "de778f2b", + "id": "92af6100", + "metadata": { + "editable": true + }, + "source": [ + "## Material for the active learning sessions Tuesday and Wednesday" + ] + }, + { + "cell_type": "markdown", + "id": "289087d3", "metadata": { "editable": true }, @@ -60,7 +71,7 @@ }, { "cell_type": "markdown", - "id": "ca2b6500", + "id": "dec4f46f", "metadata": { "editable": true }, @@ -72,7 +83,7 @@ }, { "cell_type": "markdown", - "id": "a42c6c2d", + "id": "dc52e1c9", "metadata": { "editable": true }, @@ -84,7 +95,7 @@ }, { "cell_type": "markdown", - "id": "b42bcaa4", + "id": "778e061e", "metadata": { "editable": true }, @@ -94,7 +105,7 @@ }, { "cell_type": "markdown", - "id": "e208741e", + "id": "e0b29417", "metadata": { "editable": true }, @@ -106,7 +117,7 @@ }, { "cell_type": "markdown", - "id": "1ca945f1", + "id": "b9a47c36", "metadata": { "editable": true }, @@ -116,7 +127,7 @@ }, { "cell_type": "markdown", - "id": "0df614ad", + "id": "0e7ba13f", "metadata": { "editable": true }, @@ -133,7 +144,7 @@ }, { "cell_type": "markdown", - "id": "07ba6f53", + "id": "440f1b7e", "metadata": { "editable": true }, @@ -143,7 +154,7 @@ }, { "cell_type": "markdown", - "id": "05d566fa", + "id": "c82e2760", "metadata": { "editable": true }, @@ -155,7 +166,7 @@ }, { "cell_type": "markdown", - "id": "bef58181", + "id": "822670fb", "metadata": { "editable": true }, @@ -165,7 +176,7 @@ }, { "cell_type": "markdown", - "id": "88faff60", + "id": "91ad3b47", "metadata": { "editable": true }, @@ -177,7 +188,7 @@ }, { "cell_type": "markdown", - "id": "78db1996", + "id": "39f3629f", "metadata": { "editable": true }, @@ -191,7 +202,7 @@ }, { "cell_type": "markdown", - "id": "bacb305d", + "id": "3656f362", "metadata": { "editable": true }, @@ -203,7 +214,7 @@ }, { "cell_type": "markdown", - "id": "f72c3acc", + "id": "607c77e0", "metadata": { "editable": true }, @@ -225,7 +236,7 @@ }, { "cell_type": "markdown", - "id": "70d77e0a", + "id": "3c860ef3", "metadata": { "editable": true }, @@ -237,7 +248,7 @@ }, { "cell_type": "markdown", - "id": "4e09c60a", + "id": "5e180c8a", "metadata": { "editable": true }, @@ -252,7 +263,7 @@ }, { "cell_type": "markdown", - "id": "454ed107", + "id": "898d8de3", "metadata": { "editable": true }, @@ -264,7 +275,7 @@ }, { "cell_type": "markdown", - "id": "e680ab8d", + "id": "22cb9718", "metadata": { "editable": true }, @@ -276,7 +287,7 @@ }, { "cell_type": "markdown", - "id": "55e8064a", + "id": "5c2265fe", "metadata": { "editable": true }, @@ -286,7 +297,7 @@ }, { "cell_type": "markdown", - "id": "54323d93", + "id": "83081288", "metadata": { "editable": true }, @@ -298,7 +309,7 @@ }, { "cell_type": "markdown", - "id": "11308aeb", + "id": "626bcbf8", "metadata": { "editable": true }, @@ -308,7 +319,7 @@ }, { "cell_type": "markdown", - "id": "e6329c2b", + "id": "f9ad9b1a", "metadata": { "editable": true }, @@ -320,7 +331,7 @@ }, { "cell_type": "markdown", - "id": "850c985b", + "id": "87035899", "metadata": { "editable": true }, @@ -330,7 +341,7 @@ }, { "cell_type": "markdown", - "id": "967c3ea7", + "id": "e6e317a5", "metadata": { "editable": true }, @@ -342,7 +353,7 @@ }, { "cell_type": "markdown", - "id": "482029c6", + "id": "ee0cd565", "metadata": { "editable": true }, @@ -359,7 +370,7 @@ }, { "cell_type": "markdown", - "id": "dc0004a9", + "id": "6eb10b0f", "metadata": { "editable": true }, @@ -373,7 +384,7 @@ { "cell_type": "code", "execution_count": 1, - "id": "534ac439", + "id": "2a4acd2d", "metadata": { "collapsed": false, "editable": true @@ -385,7 +396,7 @@ }, { "cell_type": "markdown", - "id": "03919b93", + "id": "faa8f5ce", "metadata": { "editable": true }, @@ -396,7 +407,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "f765d0a0", + "id": "b49b7993", "metadata": { "collapsed": false, "editable": true @@ -436,7 +447,7 @@ }, { "cell_type": "markdown", - "id": "e459209e", + "id": "8f63e253", "metadata": { "editable": true }, @@ -456,7 +467,7 @@ }, { "cell_type": "markdown", - "id": "6c6da8a6", + "id": "e1120966", "metadata": { "editable": true }, @@ -468,7 +479,7 @@ }, { "cell_type": "markdown", - "id": "efd71633", + "id": "f3352999", "metadata": { "editable": true }, @@ -479,7 +490,7 @@ { "cell_type": "code", "execution_count": 3, - "id": "db9d7882", + "id": "9f34d2f0", "metadata": { "collapsed": false, "editable": true @@ -513,7 +524,7 @@ }, { "cell_type": "markdown", - "id": "7fee3c4d", + "id": "9d7a538e", "metadata": { "editable": true }, @@ -523,7 +534,7 @@ }, { "cell_type": "markdown", - "id": "09aa560a", + "id": "47bdc416", "metadata": { "editable": true }, @@ -536,7 +547,7 @@ }, { "cell_type": "markdown", - "id": "4b628c4f", + "id": "9ecebdc2", "metadata": { "editable": true }, @@ -548,7 +559,7 @@ }, { "cell_type": "markdown", - "id": "56abee21", + "id": "19f490d5", "metadata": { "editable": true }, @@ -558,7 +569,7 @@ }, { "cell_type": "markdown", - "id": "aeef03ba", + "id": "5fd6fca5", "metadata": { "editable": true }, @@ -571,7 +582,7 @@ }, { "cell_type": "markdown", - "id": "b0ded245", + "id": "7e4a2d95", "metadata": { "editable": true }, @@ -581,7 +592,7 @@ }, { "cell_type": "markdown", - "id": "832509eb", + "id": "4f2374a9", "metadata": { "editable": true }, @@ -593,7 +604,7 @@ }, { "cell_type": "markdown", - "id": "146dc50a", + "id": "43a71fde", "metadata": { "editable": true }, @@ -608,7 +619,7 @@ }, { "cell_type": "markdown", - "id": "aec12b0f", + "id": "beeb89f0", "metadata": { "editable": true }, @@ -621,7 +632,7 @@ }, { "cell_type": "markdown", - "id": "1326c8e8", + "id": "0e01d29e", "metadata": { "editable": true }, @@ -633,7 +644,7 @@ }, { "cell_type": "markdown", - "id": "b68d575d", + "id": "0610be33", "metadata": { "editable": true }, @@ -645,7 +656,7 @@ }, { "cell_type": "markdown", - "id": "11e6ed59", + "id": "2c612cc1", "metadata": { "editable": true }, @@ -655,7 +666,7 @@ }, { "cell_type": "markdown", - "id": "e6e1e17e", + "id": "cdc4949b", "metadata": { "editable": true }, @@ -668,7 +679,7 @@ }, { "cell_type": "markdown", - "id": "957ec3e8", + "id": "61fe2430", "metadata": { "editable": true }, @@ -680,7 +691,7 @@ }, { "cell_type": "markdown", - "id": "9aca13ad", + "id": "2ec8974f", "metadata": { "editable": true }, @@ -692,7 +703,7 @@ }, { "cell_type": "markdown", - "id": "786b818b", + "id": "ce2f3bc8", "metadata": { "editable": true }, @@ -704,7 +715,7 @@ }, { "cell_type": "markdown", - "id": "923eb0db", + "id": "640c5179", "metadata": { "editable": true }, @@ -716,7 +727,7 @@ }, { "cell_type": "markdown", - "id": "d65e713e", + "id": "7eaa7fc6", "metadata": { "editable": true }, @@ -730,7 +741,7 @@ }, { "cell_type": "markdown", - "id": "3392d021", + "id": "96cb4b51", "metadata": { "editable": true }, @@ -742,7 +753,7 @@ }, { "cell_type": "markdown", - "id": "beea32ad", + "id": "887e2b8e", "metadata": { "editable": true }, @@ -752,7 +763,7 @@ }, { "cell_type": "markdown", - "id": "8c9054f2", + "id": "d2d1b062", "metadata": { "editable": true }, @@ -764,7 +775,7 @@ }, { "cell_type": "markdown", - "id": "ce0df680", + "id": "c2d61418", "metadata": { "editable": true }, @@ -774,7 +785,7 @@ }, { "cell_type": "markdown", - "id": "c85bcd8f", + "id": "30191661", "metadata": { "editable": true }, @@ -786,7 +797,7 @@ }, { "cell_type": "markdown", - "id": "3d57bfb2", + "id": "9893fc88", "metadata": { "editable": true }, @@ -798,7 +809,7 @@ }, { "cell_type": "markdown", - "id": "4be71669", + "id": "3a99a8e0", "metadata": { "editable": true }, @@ -808,7 +819,7 @@ }, { "cell_type": "markdown", - "id": "78291c69", + "id": "4860197d", "metadata": { "editable": true }, @@ -819,7 +830,7 @@ }, { "cell_type": "markdown", - "id": "8e2ce9db", + "id": "8fc608c8", "metadata": { "editable": true }, @@ -831,7 +842,7 @@ }, { "cell_type": "markdown", - "id": "e5733ed1", + "id": "6980cf65", "metadata": { "editable": true }, @@ -847,7 +858,7 @@ }, { "cell_type": "markdown", - "id": "168c1b1b", + "id": "97582105", "metadata": { "editable": true }, @@ -860,7 +871,7 @@ }, { "cell_type": "markdown", - "id": "c9876061", + "id": "5a2d1f31", "metadata": { "editable": true }, @@ -872,7 +883,7 @@ }, { "cell_type": "markdown", - "id": "b5e3df11", + "id": "0fd6c833", "metadata": { "editable": true }, @@ -882,7 +893,7 @@ }, { "cell_type": "markdown", - "id": "d86a5a2a", + "id": "42fc47a0", "metadata": { "editable": true }, @@ -894,7 +905,7 @@ }, { "cell_type": "markdown", - "id": "f905e4b4", + "id": "ddf89486", "metadata": { "editable": true }, @@ -904,7 +915,7 @@ }, { "cell_type": "markdown", - "id": "ab780b24", + "id": "d8405084", "metadata": { "editable": true }, @@ -916,7 +927,7 @@ }, { "cell_type": "markdown", - "id": "d634de61", + "id": "e18c3873", "metadata": { "editable": true }, @@ -928,7 +939,7 @@ }, { "cell_type": "markdown", - "id": "670a41a0", + "id": "619a3e0b", "metadata": { "editable": true }, @@ -944,7 +955,7 @@ }, { "cell_type": "markdown", - "id": "a66e2e86", + "id": "3d710ec4", "metadata": { "editable": true }, @@ -956,7 +967,7 @@ }, { "cell_type": "markdown", - "id": "d7be9ae4", + "id": "4b93515b", "metadata": { "editable": true }, @@ -968,7 +979,7 @@ }, { "cell_type": "markdown", - "id": "417c1432", + "id": "13f9965f", "metadata": { "editable": true }, @@ -978,7 +989,7 @@ }, { "cell_type": "markdown", - "id": "bf21b1eb", + "id": "3716830b", "metadata": { "editable": true }, @@ -990,7 +1001,7 @@ }, { "cell_type": "markdown", - "id": "e8c6c561", + "id": "8560f487", "metadata": { "editable": true }, @@ -1000,7 +1011,7 @@ }, { "cell_type": "markdown", - "id": "cc83e17d", + "id": "a5ed8586", "metadata": { "editable": true }, @@ -1012,7 +1023,7 @@ }, { "cell_type": "markdown", - "id": "85e44116", + "id": "2166ee0e", "metadata": { "editable": true }, @@ -1029,7 +1040,7 @@ }, { "cell_type": "markdown", - "id": "743ab24a", + "id": "1bf4e8ba", "metadata": { "editable": true }, @@ -1041,7 +1052,7 @@ }, { "cell_type": "markdown", - "id": "cf09ce78", + "id": "d4ac9b61", "metadata": { "editable": true }, @@ -1053,7 +1064,7 @@ }, { "cell_type": "markdown", - "id": "9bdf27d8", + "id": "ca7eb968", "metadata": { "editable": true }, @@ -1063,7 +1074,7 @@ }, { "cell_type": "markdown", - "id": "1397b054", + "id": "f7e1c7fd", "metadata": { "editable": true }, @@ -1075,7 +1086,7 @@ }, { "cell_type": "markdown", - "id": "6d232041", + "id": "a916713b", "metadata": { "editable": true }, @@ -1085,7 +1096,7 @@ }, { "cell_type": "markdown", - "id": "7c743042", + "id": "f0e82317", "metadata": { "editable": true }, @@ -1097,7 +1108,7 @@ }, { "cell_type": "markdown", - "id": "ecf32c47", + "id": "027d977b", "metadata": { "editable": true }, @@ -1107,7 +1118,7 @@ }, { "cell_type": "markdown", - "id": "04d7809b", + "id": "ee77fb17", "metadata": { "editable": true }, @@ -1119,7 +1130,7 @@ }, { "cell_type": "markdown", - "id": "9ebd04d9", + "id": "45e187c5", "metadata": { "editable": true }, @@ -1129,7 +1140,7 @@ }, { "cell_type": "markdown", - "id": "b9aa9a0a", + "id": "dbcb7400", "metadata": { "editable": true }, @@ -1144,7 +1155,7 @@ }, { "cell_type": "markdown", - "id": "d912d78a", + "id": "c452f2c4", "metadata": { "editable": true }, @@ -1156,7 +1167,7 @@ }, { "cell_type": "markdown", - "id": "71180921", + "id": "f437485c", "metadata": { "editable": true }, @@ -1166,7 +1177,7 @@ }, { "cell_type": "markdown", - "id": "24877aab", + "id": "ff46e688", "metadata": { "editable": true }, @@ -1178,7 +1189,7 @@ }, { "cell_type": "markdown", - "id": "5ceac1f1", + "id": "ec2c3a4e", "metadata": { "editable": true }, @@ -1190,7 +1201,7 @@ }, { "cell_type": "markdown", - "id": "a43fbf8e", + "id": "8a5a2307", "metadata": { "editable": true }, @@ -1202,7 +1213,7 @@ }, { "cell_type": "markdown", - "id": "ada51a1b", + "id": "61b266e4", "metadata": { "editable": true }, @@ -1212,7 +1223,7 @@ }, { "cell_type": "markdown", - "id": "eccc52bb", + "id": "35e97bfb", "metadata": { "editable": true }, @@ -1224,7 +1235,7 @@ }, { "cell_type": "markdown", - "id": "83b0d869", + "id": "6824e494", "metadata": { "editable": true }, @@ -1236,7 +1247,7 @@ }, { "cell_type": "markdown", - "id": "32c3342e", + "id": "3ed3d14b", "metadata": { "editable": true }, @@ -1248,7 +1259,7 @@ }, { "cell_type": "markdown", - "id": "63ea1201", + "id": "9022e9da", "metadata": { "editable": true }, @@ -1258,7 +1269,7 @@ }, { "cell_type": "markdown", - "id": "ae009692", + "id": "66057e65", "metadata": { "editable": true }, @@ -1270,7 +1281,7 @@ }, { "cell_type": "markdown", - "id": "afbd034f", + "id": "2ac529a0", "metadata": { "editable": true }, @@ -1280,7 +1291,7 @@ }, { "cell_type": "markdown", - "id": "4917d37f", + "id": "edf0ed42", "metadata": { "editable": true }, @@ -1294,17 +1305,17 @@ }, { "cell_type": "markdown", - "id": "987f0c76", + "id": "bef83eda", "metadata": { "editable": true }, "source": [ - "Plotting these results ([figure in handwritten notes for week 36](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf)) shows clearly that Lasso regression suppresses (sets to zero) values of $\\beta_i$ for specific values of $\\lambda$. Ridge regression reduces on the other hand the values of $\\beta_i$ as function of $\\lambda$." + "Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of $\\beta_i$ for specific values of $\\lambda$. Ridge regression reduces on the other hand the values of $\\beta_i$ as function of $\\lambda$." ] }, { "cell_type": "markdown", - "id": "97d73103", + "id": "10ba1ab6", "metadata": { "editable": true }, @@ -1316,7 +1327,7 @@ }, { "cell_type": "markdown", - "id": "1bb0bc4f", + "id": "0a913bdd", "metadata": { "editable": true }, @@ -1328,7 +1339,7 @@ }, { "cell_type": "markdown", - "id": "60fa4c41", + "id": "0074bec1", "metadata": { "editable": true }, @@ -1338,7 +1349,7 @@ }, { "cell_type": "markdown", - "id": "9868a55b", + "id": "d908894e", "metadata": { "editable": true }, @@ -1350,7 +1361,7 @@ }, { "cell_type": "markdown", - "id": "e04ddc75", + "id": "acb436e8", "metadata": { "editable": true }, @@ -1360,7 +1371,7 @@ }, { "cell_type": "markdown", - "id": "50b5d084", + "id": "bfa2a7c0", "metadata": { "editable": true }, @@ -1372,7 +1383,7 @@ }, { "cell_type": "markdown", - "id": "4e7afb4b", + "id": "ca8eb48f", "metadata": { "editable": true }, @@ -1384,7 +1395,7 @@ }, { "cell_type": "markdown", - "id": "b02ec7ca", + "id": "40fb5682", "metadata": { "editable": true }, @@ -1394,7 +1405,7 @@ }, { "cell_type": "markdown", - "id": "685a6243", + "id": "fa0b61f7", "metadata": { "editable": true }, @@ -1406,7 +1417,7 @@ }, { "cell_type": "markdown", - "id": "05887870", + "id": "17950676", "metadata": { "editable": true }, @@ -1416,7 +1427,7 @@ }, { "cell_type": "markdown", - "id": "9b746aac", + "id": "4bd9e760", "metadata": { "editable": true }, @@ -1428,7 +1439,7 @@ }, { "cell_type": "markdown", - "id": "247a5768", + "id": "53b7ac04", "metadata": { "editable": true }, @@ -1440,7 +1451,7 @@ }, { "cell_type": "markdown", - "id": "4fcd1df5", + "id": "5946fdaa", "metadata": { "editable": true }, @@ -1450,7 +1461,7 @@ }, { "cell_type": "markdown", - "id": "438c8cca", + "id": "5a665fa8", "metadata": { "editable": true }, @@ -1462,7 +1473,7 @@ }, { "cell_type": "markdown", - "id": "c55b0860", + "id": "6bfb4703", "metadata": { "editable": true }, @@ -1475,7 +1486,7 @@ }, { "cell_type": "markdown", - "id": "74cf0cde", + "id": "0d65e044", "metadata": { "editable": true }, @@ -1487,7 +1498,7 @@ }, { "cell_type": "markdown", - "id": "8e25d3a0", + "id": "a329c11c", "metadata": { "editable": true }, @@ -1499,7 +1510,7 @@ }, { "cell_type": "markdown", - "id": "f2dce6dc", + "id": "db902ab8", "metadata": { "editable": true }, @@ -1511,7 +1522,7 @@ }, { "cell_type": "markdown", - "id": "7e466c2e", + "id": "8ccb1f96", "metadata": { "editable": true }, @@ -1521,7 +1532,7 @@ }, { "cell_type": "markdown", - "id": "1794597d", + "id": "518818da", "metadata": { "editable": true }, @@ -1533,7 +1544,7 @@ }, { "cell_type": "markdown", - "id": "0c2a81c3", + "id": "091ccc73", "metadata": { "editable": true }, @@ -1543,7 +1554,7 @@ }, { "cell_type": "markdown", - "id": "6078099e", + "id": "a4f7e799", "metadata": { "editable": true }, @@ -1555,7 +1566,7 @@ }, { "cell_type": "markdown", - "id": "4a82e7ac", + "id": "0a80d417", "metadata": { "editable": true }, @@ -1565,7 +1576,7 @@ }, { "cell_type": "markdown", - "id": "5c4dea33", + "id": "ac53f555", "metadata": { "editable": true }, @@ -1577,7 +1588,7 @@ }, { "cell_type": "markdown", - "id": "cb4a101d", + "id": "961a8142", "metadata": { "editable": true }, @@ -1587,7 +1598,7 @@ }, { "cell_type": "markdown", - "id": "0d32288d", + "id": "f16a9bf8", "metadata": { "editable": true }, @@ -1600,7 +1611,7 @@ }, { "cell_type": "markdown", - "id": "75dd3e83", + "id": "88e73934", "metadata": { "editable": true }, @@ -1612,7 +1623,7 @@ }, { "cell_type": "markdown", - "id": "47d4704a", + "id": "12ef013d", "metadata": { "editable": true }, @@ -1624,7 +1635,7 @@ }, { "cell_type": "markdown", - "id": "3127a2c8", + "id": "b1a05c80", "metadata": { "editable": true }, @@ -1634,7 +1645,7 @@ }, { "cell_type": "markdown", - "id": "175b8660", + "id": "dde74227", "metadata": { "editable": true }, @@ -1646,7 +1657,7 @@ }, { "cell_type": "markdown", - "id": "f820cdbe", + "id": "a7e8c2f4", "metadata": { "editable": true }, @@ -1663,7 +1674,7 @@ }, { "cell_type": "markdown", - "id": "b004066b", + "id": "0481eb81", "metadata": { "editable": true }, @@ -1675,7 +1686,7 @@ }, { "cell_type": "markdown", - "id": "4def35de", + "id": "bd95432d", "metadata": { "editable": true }, @@ -1687,7 +1698,7 @@ }, { "cell_type": "markdown", - "id": "7fdd8604", + "id": "3ecbb638", "metadata": { "editable": true }, @@ -1697,7 +1708,7 @@ }, { "cell_type": "markdown", - "id": "a33da947", + "id": "315dc174", "metadata": { "editable": true }, @@ -1709,7 +1720,7 @@ }, { "cell_type": "markdown", - "id": "8ad8d519", + "id": "4a23b51f", "metadata": { "editable": true }, @@ -1719,7 +1730,7 @@ }, { "cell_type": "markdown", - "id": "9637d8ec", + "id": "991181e5", "metadata": { "editable": true }, @@ -1731,7 +1742,7 @@ }, { "cell_type": "markdown", - "id": "a50871a8", + "id": "92ad54a5", "metadata": { "editable": true }, @@ -1741,7 +1752,7 @@ }, { "cell_type": "markdown", - "id": "2152879d", + "id": "c67d239d", "metadata": { "editable": true }, @@ -1753,7 +1764,7 @@ }, { "cell_type": "markdown", - "id": "717ca01d", + "id": "02130691", "metadata": { "editable": true }, @@ -1763,7 +1774,7 @@ }, { "cell_type": "markdown", - "id": "cbedfde8", + "id": "a7c79c97", "metadata": { "editable": true }, @@ -1778,7 +1789,7 @@ { "cell_type": "code", "execution_count": 4, - "id": "cced0760", + "id": "fa197615", "metadata": { "collapsed": false, "editable": true @@ -1840,7 +1851,7 @@ }, { "cell_type": "markdown", - "id": "5cc9d0bb", + "id": "e18f8b68", "metadata": { "editable": true }, @@ -1850,7 +1861,7 @@ }, { "cell_type": "markdown", - "id": "8f26fc0f", + "id": "c3a12d7d", "metadata": { "editable": true }, @@ -1861,7 +1872,7 @@ { "cell_type": "code", "execution_count": 5, - "id": "bf06f54c", + "id": "9b43226e", "metadata": { "collapsed": false, "editable": true @@ -1928,7 +1939,7 @@ }, { "cell_type": "markdown", - "id": "9e346aac", + "id": "becd3a54", "metadata": { "editable": true }, @@ -1939,7 +1950,7 @@ { "cell_type": "code", "execution_count": 6, - "id": "b3ce165d", + "id": "46f816fd", "metadata": { "collapsed": false, "editable": true @@ -2028,851 +2039,17 @@ }, { "cell_type": "markdown", - "id": "6c6d6c09", + "id": "59596e3e", "metadata": { "editable": true }, "source": [ - "## To think about, first part\n", - "\n", - "When you are comparing your own code with for example **Scikit-Learn**'s\n", - "library, there are some technicalities to keep in mind. The examples\n", - "here demonstrate some of these aspects with potential pitfalls.\n", - "\n", - "The discussion here focuses on the role of the intercept, how we can\n", - "set up the design matrix, what scaling we should use and other topics\n", - "which tend confuse us.\n", - "\n", - "The intercept can be interpreted as the expected value of our\n", - "target/output variables when all other predictors are set to zero.\n", - "Thus, if we cannot assume that the expected outputs/targets are zero\n", - "when all predictors are zero (the columns in the design matrix), it\n", - "may be a bad idea to implement a model which penalizes the intercept.\n", - "Furthermore, in for example Ridge and Lasso regression, the default solutions\n", - "from the library **Scikit-Learn** (when not shrinking $\\beta_0$) for the unknown parameters\n", - "$\\boldsymbol{\\beta}$, are derived under the assumption that both $\\boldsymbol{y}$ and\n", - "$\\boldsymbol{X}$ are zero centered, that is we subtract the mean values." + "## Material for lecture Thursday September 7" ] }, { "cell_type": "markdown", - "id": "6a80380c", - "metadata": { - "editable": true - }, - "source": [ - "## More thinking\n", - "\n", - "If our predictors represent different scales, then it is important to\n", - "standardize the design matrix $\\boldsymbol{X}$ by subtracting the mean of each\n", - "column from the corresponding column and dividing the column with its\n", - "standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library,\n", - "the results may differ. \n", - "\n", - "The\n", - "[Standadscaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html)\n", - "function in **Scikit-Learn** does this for us. For the data sets we\n", - "have been studying in our various examples, the data are in many cases\n", - "already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a\n", - "survey of your data, with a critical assessment of them in case you need to scale the data.\n", - "\n", - "If you need to scale the data, not doing so will give an *unfair*\n", - "penalization of the parameters since their magnitude depends on the\n", - "scale of their corresponding predictor.\n", - "\n", - "Suppose as an example that you \n", - "you have an input variable given by the heights of different persons.\n", - "Human height might be measured in inches or meters or\n", - "kilometers. If measured in kilometers, a standard linear regression\n", - "model with this predictor would probably give a much bigger\n", - "coefficient term, than if measured in millimeters.\n", - "This can clearly lead to problems in evaluating the cost/loss functions." - ] - }, - { - "cell_type": "markdown", - "id": "1f6d0596", - "metadata": { - "editable": true - }, - "source": [ - "## Still thinking\n", - "\n", - "Keep in mind that when you transform your data set before training a model, the same transformation needs to be done\n", - "on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "79e0be06", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "#Model training, we compute the mean value of y and X\n", - "y_train_mean = np.mean(y_train)\n", - "X_train_mean = np.mean(X_train,axis=0)\n", - "X_train = X_train - X_train_mean\n", - "y_train = y_train - y_train_mean\n", - "\n", - "# The we fit our model with the training data\n", - "trained_model = some_model.fit(X_train,y_train)\n", - "\n", - "\n", - "#Model prediction, we need also to transform our data set used for the prediction.\n", - "X_test = X_test - X_train_mean #Use mean from training data\n", - "y_pred = trained_model(X_test)\n", - "y_pred = y_pred + y_train_mean" - ] - }, - { - "cell_type": "markdown", - "id": "525c4ef5", - "metadata": { - "editable": true - }, - "source": [ - "## What does centering (subtracting the mean values) mean mathematically?\n", - "\n", - "Let us try to understand what this may imply mathematically when we\n", - "subtract the mean values, also known as *zero centering*. For\n", - "simplicity, we will focus on ordinary regression, as done in the above example.\n", - "\n", - "The cost/loss function for regression is" - ] - }, - { - "cell_type": "markdown", - "id": "4585e4a1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\beta_0, \\beta_1, ... , \\beta_{p-1}) = \\frac{1}{n}\\sum_{i=0}^{n} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij}\\beta_j\\right)^2,.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ba6207c3", - "metadata": { - "editable": true - }, - "source": [ - "Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.\n", - "\n", - "What we have done is to single out the $\\beta_0$ term in the definition of the mean squared error (MSE).\n", - "The design matrix\n", - "$X$ does in this case not contain any intercept column.\n", - "When we take the derivative with respect to $\\beta_0$, we want the derivative to obey" - ] - }, - { - "cell_type": "markdown", - "id": "81c29129", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial \\beta_j} = 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "67596e4b", - "metadata": { - "editable": true - }, - "source": [ - "for all $j$. For $\\beta_0$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "9bdb9d87", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial \\beta_0} = -\\frac{2}{n}\\sum_{i=0}^{n-1} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij} \\beta_j\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cb81ff47", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying away the constant $2/n$, we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "71a389fc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sum_{i=0}^{n-1} \\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} \\sum_{j=1}^{p-1} X_{ij} \\beta_j.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fa4b9339", - "metadata": { - "editable": true - }, - "source": [ - "## Further Manipulations\n", - "\n", - "Let us special first to the case where we have only two parameters $\\beta_0$ and $\\beta_1$.\n", - "Our result for $\\beta_0$ simplifies then to" - ] - }, - { - "cell_type": "markdown", - "id": "a31e16e7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "n\\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} X_{i1} \\beta_1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5d6c27e0", - "metadata": { - "editable": true - }, - "source": [ - "We obtain then" - ] - }, - { - "cell_type": "markdown", - "id": "6e855d2b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\beta_1\\frac{1}{n}\\sum_{i=0}^{n-1} X_{i1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ac3b2e85", - "metadata": { - "editable": true - }, - "source": [ - "If we define" - ] - }, - { - "cell_type": "markdown", - "id": "d677c104", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_1=\\frac{1}{n}\\sum_{i=0}^{n-1} (X_{i1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b7d4987d", - "metadata": { - "editable": true - }, - "source": [ - "and if we define the mean value of the outputs as" - ] - }, - { - "cell_type": "markdown", - "id": "f610e10c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_y=\\frac{1}{n}\\sum_{i=0}^{n-1}y_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "592c0ada", - "metadata": { - "editable": true - }, - "source": [ - "we have" - ] - }, - { - "cell_type": "markdown", - "id": "95eb9032", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\mu_y - \\beta_1\\mu_{1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6d40a325", - "metadata": { - "editable": true - }, - "source": [ - "In the general case, that is we have more parameters than $\\beta_0$ and $\\beta_1$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "a73ec1dc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\frac{1}{n}\\sum_{i=0}^{n-1}\\sum_{j=1}^{p-1} X_{ij}\\beta_j.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "110f580a", - "metadata": { - "editable": true - }, - "source": [ - "Replacing $y_i$ with $y_i - y_i - \\overline{\\boldsymbol{y}}$ and centering also our design matrix results in a cost function (in vector-matrix disguise)" - ] - }, - { - "cell_type": "markdown", - "id": "df442fd7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}) = (\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta})^T(\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4ae3df8b", - "metadata": { - "editable": true - }, - "source": [ - "## Wrapping it up\n", - "\n", - "If we minimize with respect to $\\boldsymbol{\\beta}$ we have then" - ] - }, - { - "cell_type": "markdown", - "id": "145ac8a9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X})^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2ebb35d5", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{\\tilde{y}} = \\boldsymbol{y} - \\overline{\\boldsymbol{y}}$\n", - "and $\\tilde{X}_{ij} = X_{ij} - \\frac{1}{n}\\sum_{k=0}^{n-1}X_{kj}$.\n", - "\n", - "For Ridge regression we need to add $\\lambda \\boldsymbol{\\beta}^T\\boldsymbol{\\beta}$ to the cost function and get then" - ] - }, - { - "cell_type": "markdown", - "id": "3f2293ec", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X} + \\lambda I)^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "73504771", - "metadata": { - "editable": true - }, - "source": [ - "What does this mean? And why do we insist on all this? Let us look at some examples." - ] - }, - { - "cell_type": "markdown", - "id": "3d935fba", - "metadata": { - "editable": true - }, - "source": [ - "## Linear Regression code, Intercept handling first\n", - "\n", - "This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (*code example thanks to Øyvind Sigmundson Schøyen*). Here our scaling of the data is done by subtracting the mean values only.\n", - "Note also that we do not split the data into training and test." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "c109b1b5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "\n", - "np.random.seed(2021)\n", - "\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", - "\n", - "def fit_beta(X, y):\n", - " return np.linalg.pinv(X.T @ X) @ X.T @ y\n", - "\n", - "\n", - "true_beta = [2, 0.5, 3.7]\n", - "\n", - "x = np.linspace(0, 1, 11)\n", - "y = np.sum(\n", - " np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0\n", - ") + 0.1 * np.random.normal(size=len(x))\n", - "\n", - "degree = 3\n", - "X = np.zeros((len(x), degree))\n", - "\n", - "# Include the intercept in the design matrix\n", - "for p in range(degree):\n", - " X[:, p] = x ** p\n", - "\n", - "beta = fit_beta(X, y)\n", - "\n", - "# Intercept is included in the design matrix\n", - "skl = LinearRegression(fit_intercept=False).fit(X, y)\n", - "\n", - "print(f\"True beta: {true_beta}\")\n", - "print(f\"Fitted beta: {beta}\")\n", - "print(f\"Sklearn fitted beta: {skl.coef_}\")\n", - "ypredictOwn = X @ beta\n", - "ypredictSKL = skl.predict(X)\n", - "print(f\"MSE with intercept column\")\n", - "print(MSE(y,ypredictOwn))\n", - "print(f\"MSE with intercept column from SKL\")\n", - "print(MSE(y,ypredictSKL))\n", - "\n", - "\n", - "plt.figure()\n", - "plt.scatter(x, y, label=\"Data\")\n", - "plt.plot(x, X @ beta, label=\"Fit\")\n", - "plt.plot(x, skl.predict(X), label=\"Sklearn (fit_intercept=False)\")\n", - "\n", - "\n", - "# Do not include the intercept in the design matrix\n", - "X = np.zeros((len(x), degree - 1))\n", - "\n", - "for p in range(degree - 1):\n", - " X[:, p] = x ** (p + 1)\n", - "\n", - "# Intercept is not included in the design matrix\n", - "skl = LinearRegression(fit_intercept=True).fit(X, y)\n", - "\n", - "# Use centered values for X and y when computing coefficients\n", - "y_offset = np.average(y, axis=0)\n", - "X_offset = np.average(X, axis=0)\n", - "\n", - "beta = fit_beta(X - X_offset, y - y_offset)\n", - "intercept = np.mean(y_offset - X_offset @ beta)\n", - "\n", - "print(f\"Manual intercept: {intercept}\")\n", - "print(f\"Fitted beta (wiothout intercept): {beta}\")\n", - "print(f\"Sklearn intercept: {skl.intercept_}\")\n", - "print(f\"Sklearn fitted beta (without intercept): {skl.coef_}\")\n", - "ypredictOwn = X @ beta\n", - "ypredictSKL = skl.predict(X)\n", - "print(f\"MSE with Manual intercept\")\n", - "print(MSE(y,ypredictOwn+intercept))\n", - "print(f\"MSE with Sklearn intercept\")\n", - "print(MSE(y,ypredictSKL))\n", - "\n", - "plt.plot(x, X @ beta + intercept, \"--\", label=\"Fit (manual intercept)\")\n", - "plt.plot(x, skl.predict(X), \"--\", label=\"Sklearn (fit_intercept=True)\")\n", - "plt.grid()\n", - "plt.legend()\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "534b2f34", - "metadata": { - "editable": true - }, - "source": [ - "The intercept is the value of our output/target variable\n", - "when all our features are zero and our function crosses the $y$-axis (for a one-dimensional case). \n", - "\n", - "Printing the MSE, we see first that both methods give the same MSE, as\n", - "they should. However, when we move to for example Ridge regression,\n", - "the way we treat the intercept may give a larger or smaller MSE,\n", - "meaning that the MSE can be penalized by the value of the\n", - "intercept. Not including the intercept in the fit, means that the\n", - "regularization term does not include $\\beta_0$. For different values\n", - "of $\\lambda$, this may lead to differeing MSE values. \n", - "\n", - "To remind the reader, the regularization term, with the intercept in Ridge regression is given by" - ] - }, - { - "cell_type": "markdown", - "id": "622d039d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=0}^{p-1}\\beta_j^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c6b33efa", - "metadata": { - "editable": true - }, - "source": [ - "but when we take out the intercept, this equation becomes" - ] - }, - { - "cell_type": "markdown", - "id": "c184e92a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=1}^{p-1}\\beta_j^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "61f55115", - "metadata": { - "editable": true - }, - "source": [ - "For Lasso regression we have" - ] - }, - { - "cell_type": "markdown", - "id": "4aa4ba1c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_1 = \\lambda \\sum_{j=1}^{p-1}\\vert\\beta_j\\vert.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "534a2cca", - "metadata": { - "editable": true - }, - "source": [ - "It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get a MSE which then contains the intercept." - ] - }, - { - "cell_type": "markdown", - "id": "c45e132c", - "metadata": { - "editable": true - }, - "source": [ - "## Code Examples\n", - "\n", - "Armed with this wisdom, we attempt first to simply set the intercept equal to **False** in our implementation of Ridge regression for our well-known vanilla data set." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "63d15269", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "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", - "from sklearn import linear_model\n", - "\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", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(3155)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)\n", - "\n", - "Maxpolydegree = 20\n", - "X = np.zeros((n,Maxpolydegree))\n", - "#We include explicitely the intercept column\n", - "for degree in range(Maxpolydegree):\n", - " X[:,degree] = x**degree\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "p = Maxpolydegree\n", - "I = np.eye(p,p)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 6\n", - "MSEOwnRidgePredict = np.zeros(nlambdas)\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 2, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n", - " # Note: we include the intercept column and no scaling\n", - " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n", - " RegRidge.fit(X_train,y_train)\n", - " # and then make the prediction\n", - " ytildeOwnRidge = X_train @ OwnRidgeBeta\n", - " ypredictOwnRidge = X_test @ OwnRidgeBeta\n", - " ytildeRidge = RegRidge.predict(X_train)\n", - " ypredictRidge = RegRidge.predict(X_test)\n", - " MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)\n", - " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", - " print(\"Beta values for own Ridge implementation\")\n", - " print(OwnRidgeBeta)\n", - " print(\"Beta values for Scikit-Learn Ridge implementation\")\n", - " print(RegRidge.coef_)\n", - " print(\"MSE values for own Ridge implementation\")\n", - " print(MSEOwnRidgePredict[i])\n", - " print(\"MSE values for Scikit-Learn Ridge implementation\")\n", - " print(MSERidgePredict[i])\n", - "\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')\n", - "\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "62fa350a", - "metadata": { - "editable": true - }, - "source": [ - "The results here agree when we force **Scikit-Learn**'s Ridge function to include the first column in our design matrix.\n", - "We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix.\n", - "What happens if we do not include the intercept in our fit?\n", - "Let us see how we can change this code by zero centering (thanks to Stian Bilek for inpouts here)." - ] - }, - { - "cell_type": "markdown", - "id": "d4d6005b", - "metadata": { - "editable": true - }, - "source": [ - "## Taking out the mean" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "3bac9cff", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "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", - "from sklearn import linear_model\n", - "from sklearn.preprocessing import StandardScaler\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(315)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)\n", - "\n", - "Maxpolydegree = 20\n", - "X = np.zeros((n,Maxpolydegree-1))\n", - "\n", - "for degree in range(1,Maxpolydegree): #No intercept column\n", - " X[:,degree-1] = x**(degree)\n", - "\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable\n", - "X_train_mean = np.mean(X_train,axis=0)\n", - "#Center by removing mean from each feature\n", - "X_train_scaled = X_train - X_train_mean \n", - "X_test_scaled = X_test - X_train_mean\n", - "#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered)\n", - "#Remove the intercept from the training data.\n", - "y_scaler = np.mean(y_train) \n", - "y_train_scaled = y_train - y_scaler \n", - "\n", - "p = Maxpolydegree-1\n", - "I = np.eye(p,p)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 6\n", - "MSEOwnRidgePredict = np.zeros(nlambdas)\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "\n", - "lambdas = np.logspace(-4, 2, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled)\n", - " intercept_ = y_scaler - X_train_mean@OwnRidgeBeta #The intercept can be shifted so the model can predict on uncentered data\n", - " #Add intercept to prediction\n", - " ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler \n", - " RegRidge = linear_model.Ridge(lmb)\n", - " RegRidge.fit(X_train,y_train)\n", - " ypredictRidge = RegRidge.predict(X_test)\n", - " MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)\n", - " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", - " print(\"Beta values for own Ridge implementation\")\n", - " print(OwnRidgeBeta) #Intercept is given by mean of target variable\n", - " print(\"Beta values for Scikit-Learn Ridge implementation\")\n", - " print(RegRidge.coef_)\n", - " print('Intercept from own implementation:')\n", - " print(intercept_)\n", - " print('Intercept from Scikit-Learn Ridge implementation')\n", - " print(RegRidge.intercept_)\n", - " print(\"MSE values for own Ridge implementation\")\n", - " print(MSEOwnRidgePredict[i])\n", - " print(\"MSE values for Scikit-Learn Ridge implementation\")\n", - " print(MSERidgePredict[i])\n", - "\n", - "\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'b--', label = 'MSE own Ridge Test')\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "9431aefa", - "metadata": { - "editable": true - }, - "source": [ - "We see here, when compared to the code which includes explicitely the\n", - "intercept column, that our MSE value is actually smaller. This is\n", - "because the regularization term does not include the intercept value\n", - "$\\beta_0$ in the fitting. This applies to Lasso regularization as\n", - "well. It means that our optimization is now done only with the\n", - "centered matrix and/or vector that enter the fitting procedure. Note\n", - "also that the problem with the intercept occurs mainly in these type\n", - "of polynomial fitting problem." - ] - }, - { - "cell_type": "markdown", - "id": "a06f0a20", - "metadata": { - "editable": true - }, - "source": [ - "## Friday September 9" - ] - }, - { - "cell_type": "markdown", - "id": "491bae26", + "id": "57fba84b", "metadata": { "editable": true }, @@ -2901,7 +2078,7 @@ }, { "cell_type": "markdown", - "id": "a2c774e7", + "id": "0b79f217", "metadata": { "editable": true }, @@ -2917,7 +2094,7 @@ }, { "cell_type": "markdown", - "id": "fdf93799", + "id": "bfadc49d", "metadata": { "editable": true }, @@ -2936,7 +2113,7 @@ }, { "cell_type": "markdown", - "id": "61783020", + "id": "c8c5f36d", "metadata": { "editable": true }, @@ -2950,7 +2127,7 @@ }, { "cell_type": "markdown", - "id": "579a3e8e", + "id": "0d801f58", "metadata": { "editable": true }, @@ -2962,7 +2139,7 @@ }, { "cell_type": "markdown", - "id": "8919ec8d", + "id": "b29498f7", "metadata": { "editable": true }, @@ -2973,7 +2150,7 @@ }, { "cell_type": "markdown", - "id": "8e6d1273", + "id": "10ac35c5", "metadata": { "editable": true }, @@ -2985,7 +2162,7 @@ }, { "cell_type": "markdown", - "id": "9b397651", + "id": "f80ec09c", "metadata": { "editable": true }, @@ -2997,7 +2174,7 @@ }, { "cell_type": "markdown", - "id": "b87296ba", + "id": "458211cd", "metadata": { "editable": true }, @@ -3013,7 +2190,7 @@ }, { "cell_type": "markdown", - "id": "075a29e0", + "id": "6a995ee9", "metadata": { "editable": true }, @@ -3024,7 +2201,7 @@ }, { "cell_type": "markdown", - "id": "ab22e3a9", + "id": "7e11465e", "metadata": { "editable": true }, @@ -3047,7 +2224,7 @@ }, { "cell_type": "markdown", - "id": "8064c896", + "id": "c3c1ff49", "metadata": { "editable": true }, @@ -3058,7 +2235,7 @@ }, { "cell_type": "markdown", - "id": "9ecea4d2", + "id": "ddcc761e", "metadata": { "editable": true }, @@ -3070,7 +2247,7 @@ }, { "cell_type": "markdown", - "id": "ddbbbf7e", + "id": "101539f6", "metadata": { "editable": true }, @@ -3082,7 +2259,7 @@ }, { "cell_type": "markdown", - "id": "2d2e304c", + "id": "a0540e76", "metadata": { "editable": true }, @@ -3096,7 +2273,7 @@ }, { "cell_type": "markdown", - "id": "8902a5b2", + "id": "e036abed", "metadata": { "editable": true }, @@ -3127,7 +2304,7 @@ }, { "cell_type": "markdown", - "id": "33a2838d", + "id": "1a602124", "metadata": { "editable": true }, @@ -3149,7 +2326,7 @@ }, { "cell_type": "markdown", - "id": "85db379b", + "id": "f32395e8", "metadata": { "editable": true }, @@ -3161,7 +2338,7 @@ }, { "cell_type": "markdown", - "id": "18c22f28", + "id": "196b5a71", "metadata": { "editable": true }, @@ -3174,7 +2351,7 @@ }, { "cell_type": "markdown", - "id": "8bc69031", + "id": "8b444609", "metadata": { "editable": true }, @@ -3186,7 +2363,7 @@ }, { "cell_type": "markdown", - "id": "d6544f85", + "id": "e2aa4dea", "metadata": { "editable": true }, @@ -3198,7 +2375,7 @@ }, { "cell_type": "markdown", - "id": "2457b453", + "id": "d681a7f9", "metadata": { "editable": true }, @@ -3210,7 +2387,7 @@ }, { "cell_type": "markdown", - "id": "b051314b", + "id": "cf4c0fb3", "metadata": { "editable": true }, @@ -3222,7 +2399,7 @@ }, { "cell_type": "markdown", - "id": "cfda23b3", + "id": "708f7d10", "metadata": { "editable": true }, @@ -3245,7 +2422,7 @@ }, { "cell_type": "markdown", - "id": "a23408ee", + "id": "6dab5a6e", "metadata": { "editable": true }, @@ -3257,7 +2434,7 @@ }, { "cell_type": "markdown", - "id": "202e37fb", + "id": "958c835b", "metadata": { "editable": true }, @@ -3270,7 +2447,7 @@ }, { "cell_type": "markdown", - "id": "dbcf24e6", + "id": "58b97d31", "metadata": { "editable": true }, @@ -3282,7 +2459,7 @@ }, { "cell_type": "markdown", - "id": "06ceed52", + "id": "f319e10b", "metadata": { "editable": true }, @@ -3294,7 +2471,7 @@ }, { "cell_type": "markdown", - "id": "a7fb86c6", + "id": "8ed63d03", "metadata": { "editable": true }, @@ -3306,7 +2483,7 @@ }, { "cell_type": "markdown", - "id": "05f05891", + "id": "c3e14c22", "metadata": { "editable": true }, @@ -3317,7 +2494,7 @@ }, { "cell_type": "markdown", - "id": "b94d1190", + "id": "64fc5cd4", "metadata": { "editable": true }, @@ -3329,7 +2506,7 @@ }, { "cell_type": "markdown", - "id": "d4c0ad8e", + "id": "b2256460", "metadata": { "editable": true }, @@ -3340,7 +2517,7 @@ }, { "cell_type": "markdown", - "id": "65a46e42", + "id": "87c5772f", "metadata": { "editable": true }, @@ -3352,7 +2529,7 @@ }, { "cell_type": "markdown", - "id": "679d99d2", + "id": "ad4425cc", "metadata": { "editable": true }, @@ -3362,7 +2539,7 @@ }, { "cell_type": "markdown", - "id": "d4362fd5", + "id": "33d200c8", "metadata": { "editable": true }, @@ -3393,7 +2570,7 @@ }, { "cell_type": "markdown", - "id": "9e242cda", + "id": "0ccf81a4", "metadata": { "editable": true }, @@ -3405,7 +2582,7 @@ }, { "cell_type": "markdown", - "id": "a7543db7", + "id": "65442e18", "metadata": { "editable": true }, @@ -3417,7 +2594,7 @@ }, { "cell_type": "markdown", - "id": "fcc3cb78", + "id": "746181e3", "metadata": { "editable": true }, @@ -3427,7 +2604,7 @@ }, { "cell_type": "markdown", - "id": "f76e3a84", + "id": "8db48c8a", "metadata": { "editable": true }, @@ -3439,7 +2616,7 @@ }, { "cell_type": "markdown", - "id": "aaacd43a", + "id": "444ed592", "metadata": { "editable": true }, @@ -3449,7 +2626,7 @@ }, { "cell_type": "markdown", - "id": "44194843", + "id": "cb663e4b", "metadata": { "editable": true }, @@ -3461,7 +2638,7 @@ }, { "cell_type": "markdown", - "id": "a1203a00", + "id": "c650bff3", "metadata": { "editable": true }, @@ -3471,7 +2648,7 @@ }, { "cell_type": "markdown", - "id": "cfb9ea5c", + "id": "5eca9ec1", "metadata": { "editable": true }, @@ -3483,7 +2660,7 @@ }, { "cell_type": "markdown", - "id": "5eb9a0ea", + "id": "faa327ae", "metadata": { "editable": true }, @@ -3493,7 +2670,7 @@ }, { "cell_type": "markdown", - "id": "147ba03e", + "id": "31fc1a2b", "metadata": { "editable": true }, @@ -3513,7 +2690,7 @@ }, { "cell_type": "markdown", - "id": "15b862d7", + "id": "3619de6c", "metadata": { "editable": true }, @@ -3525,7 +2702,7 @@ }, { "cell_type": "markdown", - "id": "c0ed74ec", + "id": "52da2f98", "metadata": { "editable": true }, @@ -3535,7 +2712,7 @@ }, { "cell_type": "markdown", - "id": "1e5c85a3", + "id": "890c2fed", "metadata": { "editable": true }, @@ -3547,7 +2724,7 @@ }, { "cell_type": "markdown", - "id": "eb1ad707", + "id": "c2db0804", "metadata": { "editable": true }, @@ -3559,7 +2736,7 @@ }, { "cell_type": "markdown", - "id": "f5862c9a", + "id": "65615dc3", "metadata": { "editable": true }, @@ -3571,7 +2748,7 @@ }, { "cell_type": "markdown", - "id": "a93994dd", + "id": "2c21bbaa", "metadata": { "editable": true }, @@ -3583,7 +2760,7 @@ }, { "cell_type": "markdown", - "id": "48362ea4", + "id": "1e96b67f", "metadata": { "editable": true }, @@ -3595,7 +2772,7 @@ }, { "cell_type": "markdown", - "id": "a736264f", + "id": "70c1bd4d", "metadata": { "editable": true }, @@ -3607,7 +2784,7 @@ }, { "cell_type": "markdown", - "id": "2ca55904", + "id": "a5a71be1", "metadata": { "editable": true }, @@ -3619,7 +2796,7 @@ }, { "cell_type": "markdown", - "id": "3232736a", + "id": "3d30a931", "metadata": { "editable": true }, @@ -3631,7 +2808,7 @@ }, { "cell_type": "markdown", - "id": "a05c0eb9", + "id": "4a9afe64", "metadata": { "editable": true }, @@ -3641,7 +2818,7 @@ }, { "cell_type": "markdown", - "id": "2d8a77dc", + "id": "76da1daa", "metadata": { "editable": true }, @@ -3653,7 +2830,7 @@ }, { "cell_type": "markdown", - "id": "c2983edd", + "id": "e3134714", "metadata": { "editable": true }, @@ -3663,7 +2840,7 @@ }, { "cell_type": "markdown", - "id": "285d34f1", + "id": "ff0ea1cd", "metadata": { "editable": true }, @@ -3682,7 +2859,7 @@ }, { "cell_type": "markdown", - "id": "4daab924", + "id": "229aa3b3", "metadata": { "editable": true }, @@ -3703,7 +2880,7 @@ }, { "cell_type": "markdown", - "id": "134a7757", + "id": "c5ac1aae", "metadata": { "editable": true }, @@ -3715,7 +2892,7 @@ }, { "cell_type": "markdown", - "id": "c43dde74", + "id": "954824fd", "metadata": { "editable": true }, @@ -3726,7 +2903,7 @@ }, { "cell_type": "markdown", - "id": "18a5f41d", + "id": "7633d6dd", "metadata": { "editable": true }, @@ -3739,7 +2916,7 @@ }, { "cell_type": "markdown", - "id": "31edd0a3", + "id": "526a8146", "metadata": { "editable": true }, @@ -3751,7 +2928,7 @@ }, { "cell_type": "markdown", - "id": "f9171778", + "id": "fb5827c4", "metadata": { "editable": true }, @@ -3761,7 +2938,7 @@ }, { "cell_type": "markdown", - "id": "33f83b25", + "id": "ec6100c3", "metadata": { "editable": true }, @@ -3773,7 +2950,7 @@ }, { "cell_type": "markdown", - "id": "b23ddfdd", + "id": "5f8cb0aa", "metadata": { "editable": true }, @@ -3783,7 +2960,7 @@ }, { "cell_type": "markdown", - "id": "0c52e6db", + "id": "90f52404", "metadata": { "editable": true }, @@ -3795,7 +2972,7 @@ }, { "cell_type": "markdown", - "id": "bcbb9fb7", + "id": "16e14546", "metadata": { "editable": true }, @@ -3805,7 +2982,7 @@ }, { "cell_type": "markdown", - "id": "5d5effd4", + "id": "ae7afa6d", "metadata": { "editable": true }, @@ -3822,7 +2999,7 @@ }, { "cell_type": "markdown", - "id": "12191b9e", + "id": "7b6a425c", "metadata": { "editable": true }, @@ -3840,8 +3017,8 @@ }, { "cell_type": "code", - "execution_count": 11, - "id": "80b8d381", + "execution_count": 7, + "id": "a6e3c0ad", "metadata": { "collapsed": false, "editable": true @@ -3915,7 +3092,7 @@ }, { "cell_type": "markdown", - "id": "3d846a7b", + "id": "7d8148fc", "metadata": { "editable": true }, @@ -3925,7 +3102,7 @@ }, { "cell_type": "markdown", - "id": "cdba3cee", + "id": "614e8634", "metadata": { "editable": true }, @@ -3939,7 +3116,7 @@ }, { "cell_type": "markdown", - "id": "f2f7790a", + "id": "37fa6822", "metadata": { "editable": true }, @@ -3951,7 +3128,7 @@ }, { "cell_type": "markdown", - "id": "14655685", + "id": "37f0743c", "metadata": { "editable": true }, @@ -3961,7 +3138,7 @@ }, { "cell_type": "markdown", - "id": "a87a0d7d", + "id": "238ed35a", "metadata": { "editable": true }, @@ -3973,7 +3150,7 @@ }, { "cell_type": "markdown", - "id": "c49cf8f2", + "id": "219f1556", "metadata": { "editable": true }, @@ -3983,7 +3160,7 @@ }, { "cell_type": "markdown", - "id": "093333d4", + "id": "0706cf9e", "metadata": { "editable": true }, @@ -3995,7 +3172,7 @@ }, { "cell_type": "markdown", - "id": "1b9fa92a", + "id": "4caa60d9", "metadata": { "editable": true }, @@ -4005,7 +3182,7 @@ }, { "cell_type": "markdown", - "id": "53c11861", + "id": "eac35960", "metadata": { "editable": true }, @@ -4017,7 +3194,7 @@ }, { "cell_type": "markdown", - "id": "2f8298c1", + "id": "6a67663d", "metadata": { "editable": true }, @@ -4027,7 +3204,7 @@ }, { "cell_type": "markdown", - "id": "87d74e6a", + "id": "0d7f08cb", "metadata": { "editable": true }, @@ -4043,7 +3220,7 @@ }, { "cell_type": "markdown", - "id": "a049d0ea", + "id": "1dc770da", "metadata": { "editable": true }, @@ -4055,7 +3232,7 @@ }, { "cell_type": "markdown", - "id": "423dbbec", + "id": "ac7359f8", "metadata": { "editable": true }, @@ -4065,7 +3242,7 @@ }, { "cell_type": "markdown", - "id": "8f81c0dd", + "id": "e524e9cc", "metadata": { "editable": true }, @@ -4077,7 +3254,7 @@ }, { "cell_type": "markdown", - "id": "d44ba548", + "id": "165565d5", "metadata": { "editable": true }, @@ -4090,7 +3267,7 @@ }, { "cell_type": "markdown", - "id": "759e1a46", + "id": "4e4ff218", "metadata": { "editable": true }, @@ -4102,7 +3279,7 @@ }, { "cell_type": "markdown", - "id": "32b1de62", + "id": "00b53e65", "metadata": { "editable": true }, @@ -4112,7 +3289,7 @@ }, { "cell_type": "markdown", - "id": "2378e1f6", + "id": "3d4d1abe", "metadata": { "editable": true }, @@ -4124,7 +3301,7 @@ }, { "cell_type": "markdown", - "id": "787f1ed7", + "id": "fad0d46d", "metadata": { "editable": true }, @@ -4134,7 +3311,7 @@ }, { "cell_type": "markdown", - "id": "401c6c4e", + "id": "974746aa", "metadata": { "editable": true }, @@ -4146,7 +3323,7 @@ }, { "cell_type": "markdown", - "id": "3f7aece4", + "id": "0b0fece4", "metadata": { "editable": true }, @@ -4158,7 +3335,7 @@ }, { "cell_type": "markdown", - "id": "deb8ed7f", + "id": "0f05f622", "metadata": { "editable": true }, @@ -4168,7 +3345,7 @@ }, { "cell_type": "markdown", - "id": "354d2fea", + "id": "ed87949b", "metadata": { "editable": true }, @@ -4180,7 +3357,7 @@ }, { "cell_type": "markdown", - "id": "834e893c", + "id": "678ca6bc", "metadata": { "editable": true }, @@ -4192,7 +3369,7 @@ }, { "cell_type": "markdown", - "id": "9f14f991", + "id": "642ac33f", "metadata": { "editable": true }, @@ -4204,7 +3381,7 @@ }, { "cell_type": "markdown", - "id": "e749f01f", + "id": "9e80553a", "metadata": { "editable": true }, @@ -4214,7 +3391,7 @@ }, { "cell_type": "markdown", - "id": "06f11820", + "id": "25707056", "metadata": { "editable": true }, @@ -4226,243 +3403,13 @@ }, { "cell_type": "markdown", - "id": "94c9065c", + "id": "95fed8fb", "metadata": { "editable": true }, "source": [ "which is our Lasso cost function!" ] - }, - { - "cell_type": "markdown", - "id": "20c64501", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 1: mean values and variances in linear regression\n", - "\n", - "This exercise deals with various mean values ad variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of [Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer](https://www.springer.com/gp/book/9780387848570)).\n", - "\n", - "The assumption we have made is \n", - "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n", - "which describes our data" - ] - }, - { - "cell_type": "markdown", - "id": "bc069f72", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ee99deec", - "metadata": { - "editable": true - }, - "source": [ - "We then approximate this function with our model from the solution of the linear regression equations (ordinary least squares OLS), that is our\n", - "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we minimized $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, with" - ] - }, - { - "cell_type": "markdown", - "id": "7b02bf27", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fdfd39db", - "metadata": { - "editable": true - }, - "source": [ - "The matrix $\\boldsymbol{X}$ is the so-called design matrix." - ] - }, - { - "cell_type": "markdown", - "id": "8d268428", - "metadata": { - "editable": true - }, - "source": [ - "**a)**\n", - "Show that the expectation value of $\\boldsymbol{y}$ for a given element $i$" - ] - }, - { - "cell_type": "markdown", - "id": "23b6f545", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*} \n", - "\\mathbb{E}(y_i) & =\\mathbf{X}_{i, \\ast} \\, \\beta, \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2db7ea8d", - "metadata": { - "editable": true - }, - "source": [ - "and that\n", - "its variance is" - ] - }, - { - "cell_type": "markdown", - "id": "ce163d77", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*} \\mbox{Var}(y_i) & = \\sigma^2. \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bbd3a9ca", - "metadata": { - "editable": true - }, - "source": [ - "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n", - "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$." - ] - }, - { - "cell_type": "markdown", - "id": "11a2440e", - "metadata": { - "editable": true - }, - "source": [ - "**b)**\n", - "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ show that" - ] - }, - { - "cell_type": "markdown", - "id": "e94c5e5e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}(\\boldsymbol{\\beta}) = \\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cfaebf91", - "metadata": { - "editable": true - }, - "source": [ - "**c)**\n", - "Show finally that the variance of $\\boldsymbol{\\beta}$ is" - ] - }, - { - "cell_type": "markdown", - "id": "2fb5c3f9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{eqnarray*}\n", - "\\mbox{Var}(\\boldsymbol{\\beta}) & = & \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}.\n", - "\\end{eqnarray*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8121d786", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 2: Adding Ridge and Lasso Regression\n", - "\n", - "This exercise is a continuation of the exercises from week 35.\n", - "\n", - "We will\n", - "use the same function to generate our data set, still staying with a\n", - "simple function $y(x)$ which we want to fit using linear regression,\n", - "but now extending the analysis to include the Ridge and the Lasso\n", - "regression methods. \n", - "\n", - "We will thus again generate our own dataset for a function $y(x)$ where \n", - "$x \\in [0,1]$ and defined by random numbers computed with the uniform\n", - "distribution. The function $y$ is a quadratic polynomial in $x$ with\n", - "added stochastic noise according to the normal distribution $\\cal{N}(0,1)$.\n", - "\n", - "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "f91041e7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "x = np.random.rand(100)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100)" - ] - }, - { - "cell_type": "markdown", - "id": "df8b4c9c", - "metadata": { - "editable": true - }, - "source": [ - "**a)**\n", - "Write your own code for the Ridge method (see chapter 3.4 of Hastie *et al.*, equations (3.43) and (3.44)) and compute the parametrization for different values of $\\lambda$. Study the dependence on $\\lambda$ while also varying the strength of the noise in your expression for $y(x)$." - ] - }, - { - "cell_type": "markdown", - "id": "9acc49d5", - "metadata": { - "editable": true - }, - "source": [ - "**b)**\n", - "Our next step is to study the variance of the parameters $\\beta_1$ and $\\beta_2$ (assuming that we are parameterizing our function with a second-order polynomial). We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function or using **Scikit-Learn** to find the parameters $\\beta$. From your results calculate the variance of these parameters (recall that this is equal to the diagonal elements of the matrix $(\\hat{X}^T\\hat{X})+\\lambda\\hat{I})^{-1}$). Discuss the results of these variances as functions of $\\lambda$. In particular, try to link your discussion with the discussion in Hastie *et al.* and their figures 3.10 and 3.11. **Scikit-Learn** may not provide the variance of the parameters $\\beta$. This needs to be checked. With your own code you can however do so." - ] } ], "metadata": {}, diff --git a/doc/src/week36/.ipynb_checkpoints/exercisesweek36-checkpoint.ipynb b/doc/src/week36/.ipynb_checkpoints/exercisesweek36-checkpoint.ipynb new file mode 100644 index 000000000..28f436128 --- /dev/null +++ b/doc/src/week36/.ipynb_checkpoints/exercisesweek36-checkpoint.ipynb @@ -0,0 +1,351 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "d4ee754f", + "metadata": {}, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "443836cf", + "metadata": {}, + "source": [ + "# Exercises week 36\n", + "**September 4-8, 2023**\n", + "\n", + "Date: **Deadline is Sunday September 10 at midnight**" + ] + }, + { + "cell_type": "markdown", + "id": "52627eae", + "metadata": {}, + "source": [ + "## Overarching aims of the exercises this week\n", + "\n", + "This set of exercises form an important part of the first project. The\n", + "analytical exercises deal with the material covered last week on the\n", + "mathematical interpretations of ordinary least squares and of Ridge\n", + "regression. The numerical exercises can be seen as a continuation of\n", + "exercise 3 from week 35, with the inclusion of Ridge regression. This\n", + "material enters also the discussions of the first project." + ] + }, + { + "cell_type": "markdown", + "id": "717c36eb", + "metadata": {}, + "source": [ + "## Exercise 1: Analytical exercises\n", + "\n", + "The aim here is to derive the expression for the optimal parameters\n", + "using Ridge regression. Furthermore, using the singular value\n", + "decomposition, we will analyze the difference between the ordinary\n", + "least squares approach and Ridge regression.\n", + "\n", + "The expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n", + "our optimization problem is" + ] + }, + { + "cell_type": "markdown", + "id": "5c734a1d", + "metadata": {}, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\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": "6aaa8b49", + "metadata": {}, + "source": [ + "or we can state it as" + ] + }, + { + "cell_type": "markdown", + "id": "afbd0f2c", + "metadata": {}, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", + "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ebccf185", + "metadata": {}, + "source": [ + "where we have used the definition of a norm-2 vector, that is" + ] + }, + { + "cell_type": "markdown", + "id": "62b078ff", + "metadata": {}, + "source": [ + "$$\n", + "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "70bd79fa", + "metadata": {}, + "source": [ + "By minimizing the above equation with respect to the parameters\n", + "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", + "parameters $\\boldsymbol{\\beta}$.\n", + "\n", + "We can add a regularization parameter $\\lambda$ by\n", + "defining a new cost function to be optimized, that is" + ] + }, + { + "cell_type": "markdown", + "id": "114bf17c", + "metadata": {}, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", + "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2fcf0506", + "metadata": {}, + "source": [ + "which leads to the Ridge regression minimization problem where we\n", + "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", + "a finite number larger than zero." + ] + }, + { + "cell_type": "markdown", + "id": "ba91302c", + "metadata": {}, + "source": [ + "### a) Expression for Ridge regression\n", + "\n", + "Show that the optimal parameters" + ] + }, + { + "cell_type": "markdown", + "id": "4e86f509", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "94f90a0e", + "metadata": {}, + "source": [ + "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" + ] + }, + { + "cell_type": "markdown", + "id": "8a814dcc", + "metadata": {}, + "source": [ + "$$\n", + "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3af42292", + "metadata": {}, + "source": [ + "with $t$ a finite positive number. \n", + "\n", + "The ordinary least squares result is" + ] + }, + { + "cell_type": "markdown", + "id": "c8625097", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3a7f519d", + "metadata": {}, + "source": [ + "### b) The singular value decomposition\n", + "\n", + "Use the singular value decomposition of an $m\\times n$ matrix $\\boldsymbol{X}$ (our design matrix)" + ] + }, + { + "cell_type": "markdown", + "id": "a8ae7021", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e1d65ded", + "metadata": {}, + "source": [ + "where $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal matrices of dimensions\n", + "$m\\times m$ and $n\\times n$, respectively, and $\\boldsymbol{\\Sigma}$ is an\n", + "$m\\times n$ matrix which contains the ingular values only. This material was discussed during the lectures of week 35.\n", + "\n", + "Show that you can write the \n", + "OLS solutions in terms of the eigenvectors (the columns) of the orthogonal matrix $\\boldsymbol{U}$ as" + ] + }, + { + "cell_type": "markdown", + "id": "e147a177", + "metadata": {}, + "source": [ + "$$\n", + "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} = \\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "749540e4", + "metadata": {}, + "source": [ + "For Ridge regression, show that the corresponding equation is" + ] + }, + { + "cell_type": "markdown", + "id": "da2f753f", + "metadata": {}, + "source": [ + "$$\n", + "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b322bc70", + "metadata": {}, + "source": [ + "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n", + "\n", + "Give an interpretation of the results. Section 3.4 of Hastie et al's textbook gives a good discussion of the results." + ] + }, + { + "cell_type": "markdown", + "id": "bfaa449c", + "metadata": {}, + "source": [ + "## Exercise 2: Adding Ridge Regression\n", + "\n", + "This exercise is a continuation of exercise 3 from last week. We will use the same function to\n", + "generate our data set, still staying with a simple function $y(x)$\n", + "which we want to fit using linear regression, but now extending the\n", + "analysis to include the Ridge regression method.\n", + "\n", + "In this exercise you need to include the same elements from last week\n", + "1. Scale your data by subtracting the mean value from each column in the design matrix.\n", + "\n", + "2. Perform a split of the data in training and test set.\n", + "\n", + "The addition to the analysis this time is the introduction of the hyperparameter $\\lambda$ when introducing Ridge regression.\n", + "\n", + "Extend the code from exercise 3 from week 35 to include Ridge regression with the hyperparameter $\\lambda$. The optimal parameters $\\hat{\\beta}$ for Ridge regression can be obtained by matrix inversion in a similar way as done for ordinary least squares. You need to add to your code the following equations" + ] + }, + { + "cell_type": "markdown", + "id": "ad23d47a", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d49ef4fc", + "metadata": {}, + "source": [ + "The ordinary least squares result you encoded last week is given by" + ] + }, + { + "cell_type": "markdown", + "id": "45adbd8d", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ceac24b4", + "metadata": {}, + "source": [ + "Use these results to compute the mean squared error for ordinary least\n", + "squares and Ridge regression first for a polynomial of degree five\n", + "with $n=100$ data points and five selected values of\n", + "$\\lambda=[0.0001,0.001, 0.01,0.1,1.0]$. Compute thereafter the mean\n", + "squared error for the same values of $\\lambda$ for polynomials of degree ten\n", + "and $15$. Discuss your results for the training MSE and test MSE with\n", + "Ridge regression and ordinary least squares." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.10" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/src/week36/exercisesweek36.do.txt b/doc/src/week36/exercisesweek36.do.txt index 0a0361d8e..8bc30c848 100644 --- a/doc/src/week36/exercisesweek36.do.txt +++ b/doc/src/week36/exercisesweek36.do.txt @@ -19,14 +19,14 @@ using Ridge regression. Furthermore, using the singular value decomposition, we will analyze the difference between the ordinary least squares approach and Ridge regression. -The expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is -our optimization problem is +The expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, was given by the +optimization problem !bt \[ {\displaystyle \min_{\bm{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}. \] !et -or we can state it as +which we can also write as !bt \[ {\displaystyle \min_{\bm{\beta}\in @@ -54,9 +54,9 @@ defining a new cost function to be optimized, that is \] !et -which leads to the Ridge regression minimization problem where we -require that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is -a finite number larger than zero. +which leads to the Ridge regression minimization problem. One can require as part of the optimization problem +that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is +a finite number larger than zero. We will not implement that here. === a) Expression for Ridge regression === Show that the optimal parameters @@ -85,7 +85,7 @@ The ordinary least squares result is === b) The singular value decomposition === -Use the singular value decomposition of an $m\times n$ matrix $\bm{X}$ (our design matrix) +Use the singular value decomposition of an n\times p$ matrix $\bm{X}$ (our design matrix) !bt \[ \bm{X}=\bm{U}\bm{\Sigma}\bm{V}^T, @@ -93,8 +93,8 @@ Use the singular value decomposition of an $m\times n$ matrix $\bm{X}$ (our desi !et where $\bm{U}$ and $\bm{V}$ are orthogonal matrices of dimensions -$m\times m$ and $n\times n$, respectively, and $\bm{\Sigma}$ is an -$m\times n$ matrix which contains the ingular values only. This material was discussed during the lectures of week 35. +$n\times n$ and $p\times p$, respectively, and $\bm{\Sigma}$ is an +$n\times p$ matrix which contains the ingular values only. This material was discussed during the lectures of week 35. Show that you can write the OLS solutions in terms of the eigenvectors (the columns) of the orthogonal matrix $\bm{U}$ as @@ -115,7 +115,7 @@ For Ridge regression, show that the corresponding equation is with the vectors $\bm{u}_j$ being the columns of $\bm{U}$ from the SVD of the matrix $\bm{X}$. -Give an interpretation of the results. Section 3.4 of Hastie et al's textbook gives a good discussion of the results. +Give an interpretation of the results. "Section 3.4 of Hastie et al's textbook gives a good discussion of the above results":"https://link.springer.com/book/10.1007/978-0-387-84858-7". @@ -123,18 +123,18 @@ Give an interpretation of the results. Section 3.4 of Hastie et al's textbook g ===== Exercise: Adding Ridge Regression ===== -This exercise is a continuation of exercise 3 from last week. We will use the same function to +This exercise is a continuation of exercise 3 from week 35, see URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek35.html". We will use the same function to generate our data set, still staying with a simple function $y(x)$ which we want to fit using linear regression, but now extending the analysis to include the Ridge regression method. -In this exercise you need to include the same elements from last week -o Scale your data by subtracting the mean value from each column in the design matrix. -o Perform a split of the data in training and test set. +In this exercise you need to include the same elements from last week, that is +o scale your data by subtracting the mean value from each column in the design matrix. +o perform a split of the data in a training set and a test set. The addition to the analysis this time is the introduction of the hyperparameter $\lambda$ when introducing Ridge regression. -Extend the code from exercise 3 from week 35 to include Ridge regression with the hyperparameter $\lambda$. The optimal parameters $\hat{\beta}$ for Ridge regression can be obtained by matrix inversion in a similar way as done for ordinary least squares. You need to add to your code the following equations +Extend the code from exercise 3 from "week 35":"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek35.html" to include Ridge regression with the hyperparameter $\lambda$. The optimal parameters $\hat{\beta}$ for Ridge regression can be obtained by matrix inversion in a similar way as done for ordinary least squares. You need to add to your code the following equations !bt \[ \hat{\bm{\beta}}_{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}. diff --git a/doc/src/week36/week36.do.txt b/doc/src/week36/week36.do.txt index a6f8398a4..d8e1ec749 100644 --- a/doc/src/week36/week36.do.txt +++ b/doc/src/week36/week36.do.txt @@ -6,15 +6,16 @@ DATE: September 4-8, 2023 !split ===== Plans for week 36 ===== -* Summary from last week on discussion of SVD, Ridge and Lasso linear regression. -* Linear Regression and links with Statistics, Resampling methods and presentation of first project - -Recommended Reading: -o Lectures on Regression -o Bishop 1.1, 1.2, 2.1, 2.2, 2.3 and 3.1 -o Hastie et al chapter 3 - +o Material for the active learning sessions on Tuesday and Wednesday + o Summary from last week on discussion of SVD, Ridge and Lasso linear regression. + o Recommended Reading: Hastie et al chapter 3, see URL:"https://link.springer.com/book/10.1007/978-0-387-84858-7" + o Presentation and discussion of first project +o Material for the lecture on Thursday September 7 + o Linear Regression and links with Statistics, Resampling methods + o Recommended Reading: Hastie et al chapter 3, see URL:"https://link.springer.com/book/10.1007/978-0-387-84858-7" +!split +===== Material for the active learning sessions Tuesday and Wednesday ===== !split ===== Summary from last Week and discussion of SVD, Ridge and Lasso regression with examples ===== @@ -539,7 +540,7 @@ which leads to \] !et -Plotting these results ("figure in handwritten notes for week 36":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf") shows clearly that Lasso regression suppresses (sets to zero) values of $\beta_i$ for specific values of $\lambda$. Ridge regression reduces on the other hand the values of $\beta_i$ as function of $\lambda$. +Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of $\beta_i$ for specific values of $\lambda$. Ridge regression reduces on the other hand the values of $\beta_i$ as function of $\lambda$. @@ -915,506 +916,7 @@ plt.show() !split -===== To think about, first part ===== - -When you are comparing your own code with for example _Scikit-Learn_'s -library, there are some technicalities to keep in mind. The examples -here demonstrate some of these aspects with potential pitfalls. - -The discussion here focuses on the role of the intercept, how we can -set up the design matrix, what scaling we should use and other topics -which tend confuse us. - - - -The intercept can be interpreted as the expected value of our -target/output variables when all other predictors are set to zero. -Thus, if we cannot assume that the expected outputs/targets are zero -when all predictors are zero (the columns in the design matrix), it -may be a bad idea to implement a model which penalizes the intercept. -Furthermore, in for example Ridge and Lasso regression, the default solutions -from the library _Scikit-Learn_ (when not shrinking $\beta_0$) for the unknown parameters -$\bm{\beta}$, are derived under the assumption that both $\bm{y}$ and -$\bm{X}$ are zero centered, that is we subtract the mean values. - - -!split -===== More thinking ===== - - -If our predictors represent different scales, then it is important to -standardize the design matrix $\bm{X}$ by subtracting the mean of each -column from the corresponding column and dividing the column with its -standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, -the results may differ. - -The -"Standadscaler":"https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" -function in _Scikit-Learn_ does this for us. For the data sets we -have been studying in our various examples, the data are in many cases -already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a -survey of your data, with a critical assessment of them in case you need to scale the data. - -If you need to scale the data, not doing so will give an *unfair* -penalization of the parameters since their magnitude depends on the -scale of their corresponding predictor. - -Suppose as an example that you -you have an input variable given by the heights of different persons. -Human height might be measured in inches or meters or -kilometers. If measured in kilometers, a standard linear regression -model with this predictor would probably give a much bigger -coefficient term, than if measured in millimeters. -This can clearly lead to problems in evaluating the cost/loss functions. - - -!split -===== Still thinking ===== - -Keep in mind that when you transform your data set before training a model, the same transformation needs to be done -on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows - -!bc pycod -#Model training, we compute the mean value of y and X -y_train_mean = np.mean(y_train) -X_train_mean = np.mean(X_train,axis=0) -X_train = X_train - X_train_mean -y_train = y_train - y_train_mean - -# The we fit our model with the training data -trained_model = some_model.fit(X_train,y_train) - - -#Model prediction, we need also to transform our data set used for the prediction. -X_test = X_test - X_train_mean #Use mean from training data -y_pred = trained_model(X_test) -y_pred = y_pred + y_train_mean -!ec - - -!split -===== What does centering (subtracting the mean values) mean mathematically? ===== - - -Let us try to understand what this may imply mathematically when we -subtract the mean values, also known as *zero centering*. For -simplicity, we will focus on ordinary regression, as done in the above example. - -The cost/loss function for regression is -!bt -\[ -C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. -\] -!et -Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values. - -What we have done is to single out the $\beta_0$ term in the definition of the mean squared error (MSE). -The design matrix -$X$ does in this case not contain any intercept column. -When we take the derivative with respect to $\beta_0$, we want the derivative to obey -!bt -\[ -\frac{\partial C}{\partial \beta_j} = 0, -\] -!et - -for all $j$. For $\beta_0$ we have - -!bt -\[ -\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). -\] -!et -Multiplying away the constant $2/n$, we obtain -!bt -\[ -\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. -\] -!et - -!split -===== Further Manipulations ===== - - -Let us special first to the case where we have only two parameters $\beta_0$ and $\beta_1$. -Our result for $\beta_0$ simplifies then to -!bt -\[ -n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. -\] -!et -We obtain then -!bt -\[ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. -\] -!et -If we define -!bt -\[ -\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, -\] -!et -and if we define the mean value of the outputs as -!bt -\[ -\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, -\] -!et -we have -!bt -\[ -\beta_0 = \mu_y - \beta_1\mu_{1}. -\] -!et -In the general case, that is we have more parameters than $\beta_0$ and $\beta_1$, we have -!bt -\[ -\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. -\] -!et - - - -Replacing $y_i$ with $y_i - y_i - \overline{\bm{y}}$ and centering also our design matrix results in a cost function (in vector-matrix disguise) -!bt -\[ -C(\boldsymbol{\beta}) = (\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta})^T(\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta}). -\] -!et - -!split -===== Wrapping it up ===== - -If we minimize with respect to $\bm{\beta}$ we have then - -!bt -\[ -\hat{\bm{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, -\] -!et - -where $\boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\bm{y}}$ -and $\tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj}$. - -For Ridge regression we need to add $\lambda \boldsymbol{\beta}^T\boldsymbol{\beta}$ to the cost function and get then -!bt -\[ -\hat{\bm{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}. -\] -!et - -What does this mean? And why do we insist on all this? Let us look at some examples. - - - -!split -===== Linear Regression code, Intercept handling first ===== - -This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (*code example thanks to Øyvind Sigmundson Schøyen*). Here our scaling of the data is done by subtracting the mean values only. -Note also that we do not split the data into training and test. - -!bc pycod -import numpy as np -import matplotlib.pyplot as plt - -from sklearn.linear_model import LinearRegression - - -np.random.seed(2021) - -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - - -def fit_beta(X, y): - return np.linalg.pinv(X.T @ X) @ X.T @ y - - -true_beta = [2, 0.5, 3.7] - -x = np.linspace(0, 1, 11) -y = np.sum( - np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0 -) + 0.1 * np.random.normal(size=len(x)) - -degree = 3 -X = np.zeros((len(x), degree)) - -# Include the intercept in the design matrix -for p in range(degree): - X[:, p] = x ** p - -beta = fit_beta(X, y) - -# Intercept is included in the design matrix -skl = LinearRegression(fit_intercept=False).fit(X, y) - -print(f"True beta: {true_beta}") -print(f"Fitted beta: {beta}") -print(f"Sklearn fitted beta: {skl.coef_}") -ypredictOwn = X @ beta -ypredictSKL = skl.predict(X) -print(f"MSE with intercept column") -print(MSE(y,ypredictOwn)) -print(f"MSE with intercept column from SKL") -print(MSE(y,ypredictSKL)) - - -plt.figure() -plt.scatter(x, y, label="Data") -plt.plot(x, X @ beta, label="Fit") -plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)") - - -# Do not include the intercept in the design matrix -X = np.zeros((len(x), degree - 1)) - -for p in range(degree - 1): - X[:, p] = x ** (p + 1) - -# Intercept is not included in the design matrix -skl = LinearRegression(fit_intercept=True).fit(X, y) - -# Use centered values for X and y when computing coefficients -y_offset = np.average(y, axis=0) -X_offset = np.average(X, axis=0) - -beta = fit_beta(X - X_offset, y - y_offset) -intercept = np.mean(y_offset - X_offset @ beta) - -print(f"Manual intercept: {intercept}") -print(f"Fitted beta (wiothout intercept): {beta}") -print(f"Sklearn intercept: {skl.intercept_}") -print(f"Sklearn fitted beta (without intercept): {skl.coef_}") -ypredictOwn = X @ beta -ypredictSKL = skl.predict(X) -print(f"MSE with Manual intercept") -print(MSE(y,ypredictOwn+intercept)) -print(f"MSE with Sklearn intercept") -print(MSE(y,ypredictSKL)) - -plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)") -plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)") -plt.grid() -plt.legend() - -plt.show() - -!ec - -The intercept is the value of our output/target variable -when all our features are zero and our function crosses the $y$-axis (for a one-dimensional case). - -Printing the MSE, we see first that both methods give the same MSE, as -they should. However, when we move to for example Ridge regression, -the way we treat the intercept may give a larger or smaller MSE, -meaning that the MSE can be penalized by the value of the -intercept. Not including the intercept in the fit, means that the -regularization term does not include $\beta_0$. For different values -of $\lambda$, this may lead to differeing MSE values. - -To remind the reader, the regularization term, with the intercept in Ridge regression is given by -!bt -\[ -\lambda \vert\vert \bm{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, -\] -!et -but when we take out the intercept, this equation becomes -!bt -\[ -\lambda \vert\vert \bm{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. -\] -!et - -For Lasso regression we have -!bt -\[ -\lambda \vert\vert \bm{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. -\] -!et - -It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get a MSE which then contains the intercept. - -!split -===== Code Examples ===== - -Armed with this wisdom, we attempt first to simply set the intercept equal to _False_ in our implementation of Ridge regression for our well-known vanilla data set. - -!bc pycod -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -from sklearn import linear_model - -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(3155) - -n = 100 -x = np.random.rand(n) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) - -Maxpolydegree = 20 -X = np.zeros((n,Maxpolydegree)) -#We include explicitely the intercept column -for degree in range(Maxpolydegree): - X[:,degree] = x**degree -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) - -p = Maxpolydegree -I = np.eye(p,p) -# Decide which values of lambda to use -nlambdas = 6 -MSEOwnRidgePredict = np.zeros(nlambdas) -MSERidgePredict = np.zeros(nlambdas) -lambdas = np.logspace(-4, 2, nlambdas) -for i in range(nlambdas): - lmb = lambdas[i] - OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train - # Note: we include the intercept column and no scaling - RegRidge = linear_model.Ridge(lmb,fit_intercept=False) - RegRidge.fit(X_train,y_train) - # and then make the prediction - ytildeOwnRidge = X_train @ OwnRidgeBeta - ypredictOwnRidge = X_test @ OwnRidgeBeta - ytildeRidge = RegRidge.predict(X_train) - ypredictRidge = RegRidge.predict(X_test) - MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge) - MSERidgePredict[i] = MSE(y_test,ypredictRidge) - print("Beta values for own Ridge implementation") - print(OwnRidgeBeta) - print("Beta values for Scikit-Learn Ridge implementation") - print(RegRidge.coef_) - print("MSE values for own Ridge implementation") - print(MSEOwnRidgePredict[i]) - print("MSE values for Scikit-Learn Ridge implementation") - print(MSERidgePredict[i]) - -# Now plot the results -plt.figure() -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test') -plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test') - -plt.xlabel('log10(lambda)') -plt.ylabel('MSE') -plt.legend() -plt.show() - -!ec - -The results here agree when we force _Scikit-Learn_'s Ridge function to include the first column in our design matrix. -We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix. -What happens if we do not include the intercept in our fit? -Let us see how we can change this code by zero centering (thanks to Stian Bilek for inpouts here). - -!split -===== Taking out the mean ===== -!bc pycod -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -from sklearn import linear_model -from sklearn.preprocessing import StandardScaler - -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(315) - -n = 100 -x = np.random.rand(n) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) - -Maxpolydegree = 20 -X = np.zeros((n,Maxpolydegree-1)) - -for degree in range(1,Maxpolydegree): #No intercept column - X[:,degree-1] = x**(degree) - -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) - -#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable -X_train_mean = np.mean(X_train,axis=0) -#Center by removing mean from each feature -X_train_scaled = X_train - X_train_mean -X_test_scaled = X_test - X_train_mean -#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered) -#Remove the intercept from the training data. -y_scaler = np.mean(y_train) -y_train_scaled = y_train - y_scaler - -p = Maxpolydegree-1 -I = np.eye(p,p) -# Decide which values of lambda to use -nlambdas = 6 -MSEOwnRidgePredict = np.zeros(nlambdas) -MSERidgePredict = np.zeros(nlambdas) - -lambdas = np.logspace(-4, 2, nlambdas) -for i in range(nlambdas): - lmb = lambdas[i] - OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled) - intercept_ = y_scaler - X_train_mean@OwnRidgeBeta #The intercept can be shifted so the model can predict on uncentered data - #Add intercept to prediction - ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler - RegRidge = linear_model.Ridge(lmb) - RegRidge.fit(X_train,y_train) - ypredictRidge = RegRidge.predict(X_test) - MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge) - MSERidgePredict[i] = MSE(y_test,ypredictRidge) - print("Beta values for own Ridge implementation") - print(OwnRidgeBeta) #Intercept is given by mean of target variable - print("Beta values for Scikit-Learn Ridge implementation") - print(RegRidge.coef_) - print('Intercept from own implementation:') - print(intercept_) - print('Intercept from Scikit-Learn Ridge implementation') - print(RegRidge.intercept_) - print("MSE values for own Ridge implementation") - print(MSEOwnRidgePredict[i]) - print("MSE values for Scikit-Learn Ridge implementation") - print(MSERidgePredict[i]) - - -# Now plot the results -plt.figure() -plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'b--', label = 'MSE own Ridge Test') -plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test') -plt.xlabel('log10(lambda)') -plt.ylabel('MSE') -plt.legend() -plt.show() - -!ec - -We see here, when compared to the code which includes explicitely the -intercept column, that our MSE value is actually smaller. This is -because the regularization term does not include the intercept value -$\beta_0$ in the fitting. This applies to Lasso regularization as -well. It means that our optimization is now done only with the -centered matrix and/or vector that enter the fitting procedure. Note -also that the problem with the intercept occurs mainly in these type -of polynomial fitting problem. - - - - -!split -===== Friday September 9 ===== - +===== Material for lecture Thursday September 7 ===== !split @@ -2061,101 +1563,3 @@ which is our Lasso cost function! -===== Exercise: mean values and variances in linear regression ===== - - - -This exercise deals with various mean values ad variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of "Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer":"https://www.springer.com/gp/book/9780387848570"). - -The assumption we have made is -that there exists a function $f(\bm{x})$ and a normal distributed error $\bm{\varepsilon}\sim \mathcal{N}(0, \sigma^2)$ -which describes our data -!bt -\[ -\bm{y} = f(\bm{x})+\bm{\varepsilon} -\] -!et - -We then approximate this function with our model from the solution of the linear regression equations (ordinary least squares OLS), that is our -function $f$ is approximated by $\bm{\tilde{y}}$ where we minimized $(\bm{y}-\bm{\tilde{y}})^2$, with -!bt -\[ -\bm{\tilde{y}} = \bm{X}\bm{\beta}. -\] -!et -The matrix $\bm{X}$ is the so-called design matrix. - -!bsubex -Show that the expectation value of $\bm{y}$ for a given element $i$ -!bt -\begin{align*} -\mathbb{E}(y_i) & =\mathbf{X}_{i, \ast} \, \beta, -\end{align*} -!et -and that -its variance is -!bt -\begin{align*} \mbox{Var}(y_i) & = \sigma^2. -\end{align*} -!et -Hence, $y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \bm{\beta}, \sigma^2)$, that is $\bm{y}$ follows a normal distribution with -mean value $\bm{X}\bm{\beta}$ and variance $\sigma^2$. - -!esubex - -!bsubex -With the OLS expressions for the parameters $\bm{\beta}$ show that -!bt -\[ -\mathbb{E}(\bm{\beta}) = \bm{\beta}. -\] -!et -!esubex - -!bsubex -Show finally that the variance of $\bm{\beta}$ is -!bt -\begin{eqnarray*} -\mbox{Var}(\bm{\beta}) & = & \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}. -\end{eqnarray*} -!et - -!esubex - - -===== Exercise: Adding Ridge and Lasso Regression ===== - - -This exercise is a continuation of the exercises from week 35. - -We will -use the same function to generate our data set, still staying with a -simple function $y(x)$ which we want to fit using linear regression, -but now extending the analysis to include the Ridge and the Lasso -regression methods. - -We will thus again generate our own dataset for a function $y(x)$ where -$x \in [0,1]$ and defined by random numbers computed with the uniform -distribution. The function $y$ is a quadratic polynomial in $x$ with -added stochastic noise according to the normal distribution $\cal{N}(0,1)$. - -The following simple Python instructions define our $x$ and $y$ values (with 100 data points). -!bc pycod -x = np.random.rand(100) -y = 2.0+5*x*x+0.1*np.random.randn(100) -!ec - -!bsubex -Write your own code for the Ridge method (see chapter 3.4 of Hastie *et al.*, equations (3.43) and (3.44)) and compute the parametrization for different values of $\lambda$. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. - -!esubex - -!bsubex -Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parameterizing our function with a second-order polynomial). We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function or using _Scikit-Learn_ to find the parameters $\beta$. From your results calculate the variance of these parameters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$). Discuss the results of these variances as functions of $\lambda$. In particular, try to link your discussion with the discussion in Hastie *et al.* and their figures 3.10 and 3.11. _Scikit-Learn_ may not provide the variance of the parameters $\beta$. This needs to be checked. With your own code you can however do so. -!esubex - - - - - -