diff --git a/doc/LectureNotes/book.ipynb b/doc/LectureNotes/book.ipynb index c2fdcab63..7ae3e62cb 100644 --- a/doc/LectureNotes/book.ipynb +++ b/doc/LectureNotes/book.ipynb @@ -750,9 +750,7 @@ { "cell_type": "code", "execution_count": 1, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np" @@ -768,9 +766,7 @@ { "cell_type": "code", "execution_count": 2, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "n = 10\n", @@ -789,9 +785,7 @@ { "cell_type": "code", "execution_count": 3, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -810,9 +804,7 @@ { "cell_type": "code", "execution_count": 4, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -836,9 +828,7 @@ { "cell_type": "code", "execution_count": 5, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -860,9 +850,7 @@ { "cell_type": "code", "execution_count": 6, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -880,9 +868,7 @@ { "cell_type": "code", "execution_count": 7, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -900,9 +886,7 @@ { "cell_type": "code", "execution_count": 8, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -924,9 +908,7 @@ { "cell_type": "code", "execution_count": 9, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -944,9 +926,7 @@ { "cell_type": "code", "execution_count": 10, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -965,9 +945,7 @@ { "cell_type": "code", "execution_count": 11, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -986,9 +964,7 @@ { "cell_type": "code", "execution_count": 12, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -1008,9 +984,7 @@ { "cell_type": "code", "execution_count": 13, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -1030,9 +1004,7 @@ { "cell_type": "code", "execution_count": 14, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -1116,9 +1088,7 @@ { "cell_type": "code", "execution_count": 15, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Importing various packages\n", @@ -1141,9 +1111,7 @@ { "cell_type": "code", "execution_count": 16, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", @@ -1190,9 +1158,7 @@ { "cell_type": "code", "execution_count": 17, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", @@ -1219,9 +1185,7 @@ { "cell_type": "code", "execution_count": 18, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\n", @@ -1238,9 +1202,7 @@ { "cell_type": "code", "execution_count": 19, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "display(data_pandas.loc['Aragorn'])" @@ -1256,9 +1218,7 @@ { "cell_type": "code", "execution_count": 20, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "new_hobbit = {'First Name': [\"Peregrin\"],\n", @@ -1281,9 +1241,7 @@ { "cell_type": "code", "execution_count": 21, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -1311,9 +1269,7 @@ { "cell_type": "code", "execution_count": 22, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\n", @@ -1346,9 +1302,7 @@ { "cell_type": "code", "execution_count": 23, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "b = np.arange(16).reshape((4,4))\n", @@ -1465,9 +1419,7 @@ { "cell_type": "code", "execution_count": 24, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Importing various packages\n", @@ -1589,9 +1541,7 @@ { "cell_type": "code", "execution_count": 25, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -1633,9 +1583,7 @@ { "cell_type": "code", "execution_count": 26, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np \n", @@ -1780,9 +1728,7 @@ { "cell_type": "code", "execution_count": 27, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", @@ -1986,9 +1932,7 @@ { "cell_type": "code", "execution_count": 28, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Common imports\n", @@ -2036,9 +1980,7 @@ { "cell_type": "code", "execution_count": 29, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "from pylab import plt, mpl\n", @@ -2071,9 +2013,7 @@ { "cell_type": "code", "execution_count": 30, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "\"\"\" \n", @@ -2101,9 +2041,7 @@ { "cell_type": "code", "execution_count": 31, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Read the experimental data with Pandas\n", @@ -2145,9 +2083,7 @@ { "cell_type": "code", "execution_count": 32, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "A = Masses['A']\n", @@ -2169,9 +2105,7 @@ { "cell_type": "code", "execution_count": 33, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Now we set up the design matrix X\n", @@ -2193,9 +2127,7 @@ { "cell_type": "code", "execution_count": 34, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "clf = skl.LinearRegression().fit(X, Energies)\n", @@ -2213,9 +2145,7 @@ { "cell_type": "code", "execution_count": 35, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# The mean squared error \n", @@ -2252,9 +2182,7 @@ { "cell_type": "code", "execution_count": 36, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "\n", @@ -2302,9 +2230,7 @@ { "cell_type": "code", "execution_count": 37, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "from sklearn.neural_network import MLPRegressor\n", @@ -2699,9 +2625,7 @@ { "cell_type": "code", "execution_count": 38, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Common imports\n", @@ -3104,9 +3028,7 @@ { "cell_type": "code", "execution_count": 39, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# matrix inversion to find beta\n", @@ -3125,9 +3047,7 @@ { "cell_type": "code", "execution_count": 40, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n", @@ -3144,9 +3064,7 @@ { "cell_type": "code", "execution_count": 41, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "Masses['Eapprox'] = ytilde\n", @@ -3176,9 +3094,7 @@ { "cell_type": "code", "execution_count": 42, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "def R2(y_data, y_model):\n", @@ -3195,9 +3111,7 @@ { "cell_type": "code", "execution_count": 43, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "print(R2(Energies,ytilde))" @@ -3213,9 +3127,7 @@ { "cell_type": "code", "execution_count": 44, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "def MSE(y_data,y_model):\n", @@ -3235,9 +3147,7 @@ { "cell_type": "code", "execution_count": 45, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "def RelativeError(y_data,y_model):\n", @@ -3600,9 +3510,7 @@ { "cell_type": "code", "execution_count": 46, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Common imports\n", @@ -3720,9 +3628,7 @@ { "cell_type": "code", "execution_count": 47, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import os\n", @@ -3850,9 +3756,7 @@ { "cell_type": "code", "execution_count": 48, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -3965,9 +3869,7 @@ { "cell_type": "code", "execution_count": 49, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "X = np.zeros((n, L ** 2))\n", @@ -4029,9 +3931,7 @@ { "cell_type": "code", "execution_count": 50, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "X_train_own = np.concatenate(\n", @@ -4047,9 +3947,7 @@ { "cell_type": "code", "execution_count": 51, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", @@ -4134,9 +4032,7 @@ { "cell_type": "code", "execution_count": 52, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", @@ -4147,9 +4043,7 @@ { "cell_type": "code", "execution_count": 53, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "beta = ols_svd(X_train_own,y_train)" @@ -4165,9 +4059,7 @@ { "cell_type": "code", "execution_count": 54, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "J = beta[1:].reshape(L, L)" @@ -4183,9 +4075,7 @@ { "cell_type": "code", "execution_count": 55, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "fig = plt.figure(figsize=(20, 14))\n", @@ -6513,9 +6403,7 @@ { "cell_type": "code", "execution_count": 56, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "from numpy import *\n", @@ -6658,9 +6546,7 @@ { "cell_type": "code", "execution_count": 57, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "from numpy import *\n", @@ -6718,9 +6604,7 @@ { "cell_type": "code", "execution_count": 58, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -6949,9 +6833,7 @@ { "cell_type": "code", "execution_count": 59, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", @@ -7020,9 +6902,7 @@ { "cell_type": "code", "execution_count": 60, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", @@ -7119,9 +6999,7 @@ { "cell_type": "code", "execution_count": 61, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", @@ -7238,9 +7116,7 @@ { "cell_type": "code", "execution_count": 62, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -7346,9 +7222,7 @@ { "cell_type": "code", "execution_count": 63, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "X = np.zeros((n, L ** 2))\n", @@ -7378,9 +7252,7 @@ { "cell_type": "code", "execution_count": 64, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "clf = skl.LinearRegression().fit(X_train, y_train)" @@ -7396,9 +7268,7 @@ { "cell_type": "code", "execution_count": 65, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "J_sk = clf.coef_.reshape(L, L)" @@ -7414,9 +7284,7 @@ { "cell_type": "code", "execution_count": 66, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "fig = plt.figure(figsize=(20, 14))\n", @@ -7473,9 +7341,7 @@ { "cell_type": "code", "execution_count": 67, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "_lambda = 0.1\n", @@ -7526,9 +7392,7 @@ { "cell_type": "code", "execution_count": 68, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)\n", @@ -7563,9 +7427,7 @@ { "cell_type": "code", "execution_count": 69, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "lambdas = np.logspace(-4, 5, 10)\n", @@ -7629,9 +7491,7 @@ { "cell_type": "code", "execution_count": 70, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "fig = plt.figure(figsize=(20, 14))\n", @@ -7688,9 +7548,7 @@ { "cell_type": "code", "execution_count": 71, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "x = np.random.rand(100,1)\n", @@ -7821,9 +7679,7 @@ { "cell_type": "code", "execution_count": 72, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "x = np.random.rand(100,1)\n", @@ -7947,9 +7803,7 @@ { "cell_type": "code", "execution_count": 73, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "from mpl_toolkits.mplot3d import Axes3D\n", @@ -8570,9 +8424,7 @@ { "cell_type": "code", "execution_count": 74, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -8605,9 +8457,7 @@ { "cell_type": "code", "execution_count": 75, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -8732,9 +8582,7 @@ { "cell_type": "code", "execution_count": 76, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import pickle\n", @@ -8767,9 +8615,7 @@ { "cell_type": "code", "execution_count": 77, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "filenames = glob.glob(os.path.join(\"..\", \"dat\", \"*\"))\n", @@ -8802,9 +8648,7 @@ { "cell_type": "code", "execution_count": 78, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Set up slices of the dataset\n", @@ -8921,9 +8765,7 @@ { "cell_type": "code", "execution_count": 79, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "lambdas = np.logspace(-7, -1, 7)\n", @@ -8962,9 +8804,7 @@ { "cell_type": "code", "execution_count": 80, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "logreg_df = pd.DataFrame(clf.cv_results_)\n", @@ -9035,9 +8875,7 @@ { "cell_type": "code", "execution_count": 81, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "train_accuracy = skm.accuracy_score(y_train, clf.predict(X_train))\n", @@ -9074,9 +8912,7 @@ { "cell_type": "code", "execution_count": 82, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "fig = plt.figure(figsize=(20, 14))\n", @@ -9933,9 +9769,7 @@ { "cell_type": "code", "execution_count": 83, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -9970,9 +9804,7 @@ { "cell_type": "code", "execution_count": 84, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "pt.axis(\"equal\")\n", @@ -9990,9 +9822,7 @@ { "cell_type": "code", "execution_count": 85, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "x = guesses[-1]\n", @@ -10009,9 +9839,7 @@ { "cell_type": "code", "execution_count": 86, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "def f1d(alpha):\n", @@ -10033,9 +9861,7 @@ { "cell_type": "code", "execution_count": 87, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "pt.axis(\"equal\")\n", @@ -10632,9 +10458,7 @@ { "cell_type": "code", "execution_count": 88, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -10667,9 +10491,7 @@ { "cell_type": "code", "execution_count": 89, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "\n", @@ -10723,9 +10545,7 @@ { "cell_type": "code", "execution_count": 90, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Importing various packages\n", @@ -10808,9 +10628,7 @@ { "cell_type": "code", "execution_count": 91, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -10884,9 +10702,7 @@ { "cell_type": "code", "execution_count": 92, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -10941,9 +10757,7 @@ { "cell_type": "code", "execution_count": 93, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -10979,9 +10793,7 @@ { "cell_type": "code", "execution_count": 94, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -11033,9 +10845,7 @@ { "cell_type": "code", "execution_count": 95, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -11075,9 +10885,7 @@ { "cell_type": "code", "execution_count": 96, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -11102,9 +10910,7 @@ { "cell_type": "code", "execution_count": 97, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -11158,9 +10964,7 @@ { "cell_type": "code", "execution_count": 98, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -11184,9 +10988,7 @@ { "cell_type": "code", "execution_count": 99, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -11234,9 +11036,7 @@ { "cell_type": "code", "execution_count": 100, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -11265,9 +11065,7 @@ { "cell_type": "code", "execution_count": 101, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -11295,9 +11093,7 @@ { "cell_type": "code", "execution_count": 102, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -11327,9 +11123,7 @@ { "cell_type": "code", "execution_count": 103, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "a += b\n", @@ -11448,9 +11242,7 @@ { "cell_type": "code", "execution_count": 104, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np \n", @@ -11510,9 +11302,7 @@ { "cell_type": "code", "execution_count": 105, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np \n", @@ -11544,9 +11334,7 @@ { "cell_type": "code", "execution_count": 106, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Importing various packages\n", @@ -11980,7 +11768,25 @@ ] } ], - "metadata": {}, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, "nbformat": 4, "nbformat_minor": 2 } diff --git a/doc/pub/Regression/html/._Regression-bs000.html b/doc/pub/Regression/html/._Regression-bs000.html index aef0fd910..8df282311 100644 --- a/doc/pub/Regression/html/._Regression-bs000.html +++ b/doc/pub/Regression/html/._Regression-bs000.html @@ -400,7 +400,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Jul 22, 2019

+

Aug 17, 2019


diff --git a/doc/pub/Regression/html/._Regression-bs011.html b/doc/pub/Regression/html/._Regression-bs011.html index 9c489cc58..33f7f07b4 100644 --- a/doc/pub/Regression/html/._Regression-bs011.html +++ b/doc/pub/Regression/html/._Regression-bs011.html @@ -384,7 +384,7 @@ MathJax.Hub.Config({

Our model for the nuclear binding energies

-In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. +In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.

We restate the parts of the code we are most interested in. diff --git a/doc/pub/Regression/html/._Regression-bs013.html b/doc/pub/Regression/html/._Regression-bs013.html index e4d1547cc..0adcdeb33 100644 --- a/doc/pub/Regression/html/._Regression-bs013.html +++ b/doc/pub/Regression/html/._Regression-bs013.html @@ -393,7 +393,7 @@ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\bold $$ can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) +When linking (material below) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$ diff --git a/doc/pub/Regression/html/._Regression-bs025.html b/doc/pub/Regression/html/._Regression-bs025.html index 336b45fca..a71240cc3 100644 --- a/doc/pub/Regression/html/._Regression-bs025.html +++ b/doc/pub/Regression/html/._Regression-bs025.html @@ -474,7 +474,7 @@ plt.show()

The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. Can you give an interpretation of the various powers of \( \rho \)? +to the data.

We note also that there is a small deviation between the diff --git a/doc/pub/Regression/html/Regression-bs.html b/doc/pub/Regression/html/Regression-bs.html index aef0fd910..8df282311 100644 --- a/doc/pub/Regression/html/Regression-bs.html +++ b/doc/pub/Regression/html/Regression-bs.html @@ -400,7 +400,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Jul 22, 2019

+

Aug 17, 2019


diff --git a/doc/pub/Regression/html/Regression-reveal.html b/doc/pub/Regression/html/Regression-reveal.html index e55e0387b..62d287c35 100644 --- a/doc/pub/Regression/html/Regression-reveal.html +++ b/doc/pub/Regression/html/Regression-reveal.html @@ -148,7 +148,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

 
-

Jul 22, 2019

+

Aug 17, 2019


@@ -456,7 +456,7 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict

Our model for the nuclear binding energies

-In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. +In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.

We restate the parts of the code we are most interested in. @@ -601,7 +601,7 @@ $$

 
can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) +When linking (material below) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value

 
$$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, @@ -1156,7 +1156,7 @@ plt.show()

The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. Can you give an interpretation of the various powers of \( \rho \)? +to the data.

We note also that there is a small deviation between the diff --git a/doc/pub/Regression/html/Regression-solarized.html b/doc/pub/Regression/html/Regression-solarized.html index 6d7cff2dc..b9d5dd727 100644 --- a/doc/pub/Regression/html/Regression-solarized.html +++ b/doc/pub/Regression/html/Regression-solarized.html @@ -287,7 +287,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Jul 22, 2019

+

Aug 17, 2019












@@ -578,7 +578,7 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict

Our model for the nuclear binding energies

-In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. +In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.

We restate the parts of the code we are most interested in. @@ -714,7 +714,7 @@ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\bold $$ can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) +When linking (material below) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$ @@ -1227,7 +1227,7 @@ plt.show()

The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. Can you give an interpretation of the various powers of \( \rho \)? +to the data.

We note also that there is a small deviation between the diff --git a/doc/pub/Regression/html/Regression.html b/doc/pub/Regression/html/Regression.html index 726c4478d..d3746afeb 100644 --- a/doc/pub/Regression/html/Regression.html +++ b/doc/pub/Regression/html/Regression.html @@ -292,7 +292,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Jul 22, 2019

+

Aug 17, 2019












@@ -583,7 +583,7 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict

Our model for the nuclear binding energies

-In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. +In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.

We restate the parts of the code we are most interested in. @@ -719,7 +719,7 @@ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\bold $$ can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) +When linking (material below) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$ @@ -1232,7 +1232,7 @@ plt.show()

The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. Can you give an interpretation of the various powers of \( \rho \)? +to the data.

We note also that there is a small deviation between the diff --git a/doc/pub/Regression/ipynb/Regression.ipynb b/doc/pub/Regression/ipynb/Regression.ipynb index 6db4e651c..2ce2d2b12 100644 --- a/doc/pub/Regression/ipynb/Regression.ipynb +++ b/doc/pub/Regression/ipynb/Regression.ipynb @@ -10,7 +10,7 @@ " \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: **Jul 22, 2019**\n", + "Date: **Aug 17, 2019**\n", "\n", "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", @@ -371,7 +371,7 @@ "\n", "## Our model for the nuclear binding energies\n", "\n", - "In our [introductory notes](https://compphysics.github.io/MachineLearningMSU/doc/pub/Introduction/html/Introduction.html) we looked at the so-called [liguid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n", + "In our [introductory notes](https://compphysics.github.io/MachineLearning/doc/pub/How2ReadData/html/How2ReadData.html) we looked at the so-called [liquid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n", "\n", "We restate the parts of the code we are most interested in." ] @@ -574,7 +574,7 @@ "metadata": {}, "source": [ "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. \n", - "When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises)" + "When linking (material below) with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value" ] }, { @@ -1398,7 +1398,7 @@ "metadata": {}, "source": [ "The above simple polynomial in density $\\rho$ gives an excellent fit\n", - "to the data. Can you give an interpretation of the various powers of $\\rho$?\n", + "to the data. \n", "\n", "We note also that there is a small deviation between the\n", "standard OLS and the Ridge regression at higher densities. We discuss this in more detail\n", diff --git a/doc/pub/Regression/ipynb/ipynb-Regression-src.tar.gz b/doc/pub/Regression/ipynb/ipynb-Regression-src.tar.gz index 69eb49f3d..c37d932fc 100644 Binary files a/doc/pub/Regression/ipynb/ipynb-Regression-src.tar.gz and b/doc/pub/Regression/ipynb/ipynb-Regression-src.tar.gz differ diff --git a/doc/pub/Regression/pdf/Regression-minted.pdf b/doc/pub/Regression/pdf/Regression-minted.pdf index 33108d9e9..64ffb0d79 100644 Binary files a/doc/pub/Regression/pdf/Regression-minted.pdf and b/doc/pub/Regression/pdf/Regression-minted.pdf differ diff --git a/doc/src/Regression/.Regression-bs_html_file_collection b/doc/src/Regression/.Regression-bs_html_file_collection deleted file mode 100644 index 49f9aeeb4..000000000 --- a/doc/src/Regression/.Regression-bs_html_file_collection +++ /dev/null @@ -1,101 +0,0 @@ -Regression-bs.html -._Regression-bs000.html -._Regression-bs001.html -._Regression-bs002.html -._Regression-bs003.html -._Regression-bs004.html -._Regression-bs005.html -._Regression-bs006.html -._Regression-bs007.html -._Regression-bs008.html -._Regression-bs009.html -._Regression-bs010.html -._Regression-bs011.html -._Regression-bs012.html -._Regression-bs013.html -._Regression-bs014.html -._Regression-bs015.html -._Regression-bs016.html -._Regression-bs017.html -._Regression-bs018.html -._Regression-bs019.html -._Regression-bs020.html -._Regression-bs021.html -._Regression-bs022.html -._Regression-bs023.html -._Regression-bs024.html -._Regression-bs025.html -._Regression-bs026.html -._Regression-bs027.html -._Regression-bs028.html -._Regression-bs029.html -._Regression-bs030.html -._Regression-bs031.html -._Regression-bs032.html -._Regression-bs033.html -._Regression-bs034.html -._Regression-bs035.html -._Regression-bs036.html -._Regression-bs037.html -._Regression-bs038.html -._Regression-bs039.html -._Regression-bs040.html -._Regression-bs041.html -._Regression-bs042.html -._Regression-bs043.html -._Regression-bs044.html -._Regression-bs045.html -._Regression-bs046.html -._Regression-bs047.html -._Regression-bs048.html -._Regression-bs049.html -._Regression-bs050.html -._Regression-bs051.html -._Regression-bs052.html -._Regression-bs053.html -._Regression-bs054.html -._Regression-bs055.html -._Regression-bs056.html -._Regression-bs057.html -._Regression-bs058.html -._Regression-bs059.html -._Regression-bs060.html -._Regression-bs061.html -._Regression-bs062.html -._Regression-bs063.html -._Regression-bs064.html -._Regression-bs065.html -._Regression-bs066.html -._Regression-bs067.html -._Regression-bs068.html -._Regression-bs069.html -._Regression-bs070.html -._Regression-bs071.html -._Regression-bs072.html -._Regression-bs073.html -._Regression-bs074.html -._Regression-bs075.html -._Regression-bs076.html -._Regression-bs077.html -._Regression-bs078.html -._Regression-bs079.html -._Regression-bs080.html -._Regression-bs081.html -._Regression-bs082.html -._Regression-bs083.html -._Regression-bs084.html -._Regression-bs085.html -._Regression-bs086.html -._Regression-bs087.html -._Regression-bs088.html -._Regression-bs089.html -._Regression-bs090.html -._Regression-bs091.html -._Regression-bs092.html -._Regression-bs093.html -._Regression-bs094.html -._Regression-bs095.html -._Regression-bs096.html -._Regression-bs097.html -._Regression-bs098.html -._Regression-bs099.html diff --git a/doc/src/Regression/.Regression-reveal_html_file_collection b/doc/src/Regression/.Regression-reveal_html_file_collection deleted file mode 100644 index dcec8b30b..000000000 --- a/doc/src/Regression/.Regression-reveal_html_file_collection +++ /dev/null @@ -1,2 +0,0 @@ -Regression-reveal.html -reveal.js diff --git a/doc/src/Regression/.Regression-solarized_html_file_collection b/doc/src/Regression/.Regression-solarized_html_file_collection deleted file mode 100644 index e7f421255..000000000 --- a/doc/src/Regression/.Regression-solarized_html_file_collection +++ /dev/null @@ -1 +0,0 @@ -Regression-solarized.html diff --git a/doc/src/Regression/.Regression.copyright b/doc/src/Regression/.Regression.copyright deleted file mode 100644 index 0507b6521..000000000 --- a/doc/src/Regression/.Regression.copyright +++ /dev/null @@ -1 +0,0 @@ -{'holder': ['Morten Hjorth-Jensen'], 'year': '1999-2019', 'license': 'Released under CC Attribution-NonCommercial 4.0 license', 'cite doconce': False} \ No newline at end of file diff --git a/doc/src/Regression/.Regression_html_file_collection b/doc/src/Regression/.Regression_html_file_collection deleted file mode 100644 index b2083b0ad..000000000 --- a/doc/src/Regression/.Regression_html_file_collection +++ /dev/null @@ -1 +0,0 @@ -Regression.html diff --git a/doc/src/Regression/._Regression-bs000.html b/doc/src/Regression/._Regression-bs000.html deleted file mode 100644 index aef0fd910..000000000 --- a/doc/src/Regression/._Regression-bs000.html +++ /dev/null @@ -1,452 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - -

- - -
- -

 

 

 

- - - - - - -
-

Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis

- -

- - -

-Morten Hjorth-Jensen [1, 2] -
- -

- - -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

-

Jul 22, 2019

-
-

- - -

Read »

- - -
- -

- -

- - -
- - - - - - - -
- © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs001.html b/doc/src/Regression/._Regression-bs001.html deleted file mode 100644 index 3401b90d4..000000000 --- a/doc/src/Regression/._Regression-bs001.html +++ /dev/null @@ -1,446 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Why Linear Regression (aka Ordinary Least Squares and family)

- -

-Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \). - -

- -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. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs002.html b/doc/src/Regression/._Regression-bs002.html deleted file mode 100644 index dee6ad935..000000000 --- a/doc/src/Regression/._Regression-bs002.html +++ /dev/null @@ -1,450 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Regression analysis, overarching aims

-
-
-

- -

-Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. - -

-A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with - -

    -
  • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
  • -
  • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
  • -
  • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
  • -
- - The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. -
-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs003.html b/doc/src/Regression/._Regression-bs003.html deleted file mode 100644 index 88f261dee..000000000 --- a/doc/src/Regression/._Regression-bs003.html +++ /dev/null @@ -1,459 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Regression analysis, overarching aims II

-
-
-

- -

-Consider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix -\( \mathbf{X} \). - -

-The matrix \( \mathbf{X} \) is called the design -matrix. Additional information of the samples is available in the -form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is -generally referred to as the response variable. The aim of -regression analysis is to explain \( \boldsymbol{y} \) in terms of -\( \boldsymbol{X} \) through a functional relationship like \( y_i = -f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of -\( f(\cdot) \) is available, it is common to assume a linear relationship -between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to -the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T} \) are the regression parameters. - -

-Linear regression gives us a set of analytical equations for the parameters \( \beta_j \). - -

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs004.html b/doc/src/Regression/._Regression-bs004.html deleted file mode 100644 index 6e9d3daca..000000000 --- a/doc/src/Regression/._Regression-bs004.html +++ /dev/null @@ -1,456 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Examples

-
-
-

-In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), -consider the model we discussed for describing nuclear binding energies. - -

-There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. -Assuming -$$ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, -$$ - -we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. -This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a -\( p\times n \) matrix \( \boldsymbol{X} \). - -

-Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \) - -

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs005.html b/doc/src/Regression/._Regression-bs005.html deleted file mode 100644 index 35f7c9bdb..000000000 --- a/doc/src/Regression/._Regression-bs005.html +++ /dev/null @@ -1,449 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

General linear models

-
-
-

-Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. - -

-Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is -$$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, -$$ - -where \( \epsilon_i \) is the error in our approximation. - -

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs006.html b/doc/src/Regression/._Regression-bs006.html deleted file mode 100644 index cf2ff155f..000000000 --- a/doc/src/Regression/._Regression-bs006.html +++ /dev/null @@ -1,449 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Rewriting the fitting procedure as a linear algebra problem

-
-
-

-For every set of values \( y_i,x_i \) we have thus the corresponding set of equations -$$ -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs007.html b/doc/src/Regression/._Regression-bs007.html deleted file mode 100644 index ee1cfb7c7..000000000 --- a/doc/src/Regression/._Regression-bs007.html +++ /dev/null @@ -1,473 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Rewriting the fitting procedure as a linear algebra problem, more details

-
-
-

-Defining the vectors -$$ -\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -$$ - -and -$$ -\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -$$ - -and -$$ -\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -$$ - -and the design matrix -$$ -\boldsymbol{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -$$ - -we can rewrite our equations as -$$ -\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. -$$ - -The above design matrix is called a Vandermonde matrix. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs008.html b/doc/src/Regression/._Regression-bs008.html deleted file mode 100644 index 2976e41a3..000000000 --- a/doc/src/Regression/._Regression-bs008.html +++ /dev/null @@ -1,463 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Generalizing the fitting procedure as a linear algebra problem

-
-
-

- -

-We are obviously not limited to the above polynomial expansions. We -could replace the various powers of \( x \) with elements of Fourier -series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j -x_i)} \), or time series or other orthogonal functions. For every set -of values \( y_i,x_i \) we can then generalize the equations to - -$$ -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ - -

-Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case! -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs009.html b/doc/src/Regression/._Regression-bs009.html deleted file mode 100644 index 12a0d62fa..000000000 --- a/doc/src/Regression/._Regression-bs009.html +++ /dev/null @@ -1,460 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Generalizing the fitting procedure as a linear algebra problem

-
-
-

-We redefine in turn the matrix \( \boldsymbol{X} \) as -$$ -\boldsymbol{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -$$ - -and without loss of generality we rewrite again our equations as -$$ -\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. -$$ - -The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs010.html b/doc/src/Regression/._Regression-bs010.html deleted file mode 100644 index 96f43a65d..000000000 --- a/doc/src/Regression/._Regression-bs010.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Optimizing our parameters

-
-
-

-We have defined the matrix \( \boldsymbol{X} \) via the equations -$$ -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ - -

-As we noted above, we stayed with a system with the design matrix - \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define -our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. - -

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs011.html b/doc/src/Regression/._Regression-bs011.html deleted file mode 100644 index 9c489cc58..000000000 --- a/doc/src/Regression/._Regression-bs011.html +++ /dev/null @@ -1,523 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Our model for the nuclear binding energies

- -

-In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. - -

-We restate the parts of the code we are most interested in. -

- - -

# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("MassEval2016.dat"),'r')
-
-
-# Read the experimental data with Pandas
-Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
-              names=('N', 'Z', 'A', 'Element', 'Ebinding'),
-              widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
-              header=39,
-              index_col=False)
-
-# Extrapolated values are indicated by '#' in place of the decimal place, so
-# the Ebinding column won't be numeric. Coerce to float and drop these entries.
-Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
-Masses = Masses.dropna()
-# Convert from keV to MeV.
-Masses['Ebinding'] /= 1000
-
-# Group the DataFrame by nucleon number, A.
-Masses = Masses.groupby('A')
-# Find the rows of the grouped DataFrame with the maximum binding energy.
-Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
-A = Masses['A']
-Z = Masses['Z']
-N = Masses['N']
-Element = Masses['Element']
-Energies = Masses['Ebinding']
-
-# Now we set up the design matrix X
-X = np.zeros((len(A),5))
-X[:,0] = 1
-X[:,1] = A
-X[:,2] = A**(2.0/3.0)
-X[:,3] = A**(-1.0/3.0)
-X[:,4] = A**(-1.0)
-# Then nice printout using pandas
-DesignMatrix = pd.DataFrame(X)
-DesignMatrix.index = A
-DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
-display(DesignMatrix)
-
-

-With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as -$$ -\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, -$$ - -throughout these lectures. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs012.html b/doc/src/Regression/._Regression-bs012.html deleted file mode 100644 index 26a0feef8..000000000 --- a/doc/src/Regression/._Regression-bs012.html +++ /dev/null @@ -1,469 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Optimizing our parameters, more details

-
-
-

-With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as -$$ -\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, -$$ - -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely -$$ -C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, -$$ - -or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as -$$ -C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}. -$$ - -This function is one possible way to define the so-called cost function. - -

-It is also common to define -the function \( Q \) as - -$$ -C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, -$$ - -since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs013.html b/doc/src/Regression/._Regression-bs013.html deleted file mode 100644 index e4d1547cc..000000000 --- a/doc/src/Regression/._Regression-bs013.html +++ /dev/null @@ -1,489 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Interpretations and optimizing our parameters

-
-
-

- -

-The function -$$ -C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, -$$ - -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) -$$ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -$$ - -

-where \( \langle y_i \rangle \) is the mean value. Keep in mind also that -till now we have treated \( y_i \) as the exact value. Normally, the -response (dependent or outcome) variable \( y_i \) the outcome of a -numerical experiment or another type of experiment and is thus only an -approximation to the true value. It is then always accompanied by an -error estimate, often limited to a statistical error estimate given by -the standard deviation discussed earlier. In the discussion here we -will treat \( y_i \) as our exact value for the response variable. - -

-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem -$$ -{\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\}. -$$ - -In practical terms it means we will require -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -$$ - -which results in -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -$$ - -or in a matrix-vector form as -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). -$$ - -

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs014.html b/doc/src/Regression/._Regression-bs014.html deleted file mode 100644 index fd3112740..000000000 --- a/doc/src/Regression/._Regression-bs014.html +++ /dev/null @@ -1,471 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Interpretations and optimizing our parameters

-
-
-

-We can rewrite -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), -$$ - -as -$$ -\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, -$$ - -and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution -$$ -\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ - -

-We note also that since our design matrix is defined as \( \boldsymbol{X}\in -{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in -{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), -in our case \( p=5 \) meaning that we end up with inverting a small -\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional -matrices to invert. The methods discussed here and for many other -supervised learning algorithms like classification with logistic -regression or support vector machines, exhibit dimensionalities which -allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \). - -

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs015.html b/doc/src/Regression/._Regression-bs015.html deleted file mode 100644 index 82a9581f1..000000000 --- a/doc/src/Regression/._Regression-bs015.html +++ /dev/null @@ -1,464 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Interpretations and optimizing our parameters

-
-
-

-The residuals \( \boldsymbol{\epsilon} \) are in turn given by -$$ -\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, -$$ - -and with -$$ -\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, -$$ - -we have -$$ -\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, -$$ - -meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. - -

-

-
- - -

-Let us now return to our nuclear binding energies and simply code the above equations. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs016.html b/doc/src/Regression/._Regression-bs016.html deleted file mode 100644 index 45a289cd6..000000000 --- a/doc/src/Regression/._Regression-bs016.html +++ /dev/null @@ -1,474 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Own code for Ordinary Least Squares

- -

-It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to -write -

- - -

# matrix inversion to find beta
-beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
-# and then make the prediction
-ytilde = X @ beta
-
-

-Alternatively, you can use the least squares functionality in Numpy as -

- - -

fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
-ytildenp = np.dot(fit,X.T)
-
-

-And finally we plot our fit with and compare with data -

- - -

Masses['Eapprox']  = ytilde
-# Generate a plot comparing the experimental with the fitted values values.
-fig, ax = plt.subplots()
-ax.set_xlabel(r'$A = N + Z$')
-ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
-ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
-            label='Ame2016')
-ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
-            label='Fit')
-ax.legend()
-save_fig("Masses2016OLS")
-plt.show()
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs017.html b/doc/src/Regression/._Regression-bs017.html deleted file mode 100644 index 0ee4b2985..000000000 --- a/doc/src/Regression/._Regression-bs017.html +++ /dev/null @@ -1,473 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Adding error analysis and training set up

- -

-We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. -Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as -

- - -

def R2(y_data, y_model):
-    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
-
-

-and we would be using it as -

- - -

print(R2(Energies,ytilde))
-
-

-We can easily add our MSE score as -

- - -

def MSE(y_data,y_model):
-    n = np.size(y_model)
-    return np.sum((y_data-y_model)**2)/n
-
-print(MSE(Energies,ytilde))
-
-

-and finally the relative error as -

- - -

def RelativeError(y_data,y_model):
-    return abs((y_data-y_model)/y_data)
-print(RelativeError(Energies, ytilde))
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs018.html b/doc/src/Regression/._Regression-bs018.html deleted file mode 100644 index 7a9d6f4d6..000000000 --- a/doc/src/Regression/._Regression-bs018.html +++ /dev/null @@ -1,465 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The \( \chi^2 \) function

-
-
-

- -

-Normally, the response (dependent or outcome) variable \( y_i \) is the -outcome of a numerical experiment or another type of experiment and is -thus only an approximation to the true value. It is then always -accompanied by an error estimate, often limited to a statistical error -estimate given by the standard deviation discussed earlier. In the -discussion here we will treat \( y_i \) as our exact value for the -response variable. - -

-Introducing the standard deviation \( \sigma_i \) for each measurement -\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) -as - -$$ -\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, -$$ - -where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - -

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs019.html b/doc/src/Regression/._Regression-bs019.html deleted file mode 100644 index 3be490b51..000000000 --- a/doc/src/Regression/._Regression-bs019.html +++ /dev/null @@ -1,461 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The \( \chi^2 \) function

-
-
-

- -

-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -$$ - -which results in -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -$$ - -or in a matrix-vector form as -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). -$$ - -where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \). -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs020.html b/doc/src/Regression/._Regression-bs020.html deleted file mode 100644 index ea9d4bb03..000000000 --- a/doc/src/Regression/._Regression-bs020.html +++ /dev/null @@ -1,459 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The \( \chi^2 \) function

-
-
-

- -

-We can rewrite -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), -$$ - -as -$$ -\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, -$$ - -and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution -$$ -\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs021.html b/doc/src/Regression/._Regression-bs021.html deleted file mode 100644 index 89068013d..000000000 --- a/doc/src/Regression/._Regression-bs021.html +++ /dev/null @@ -1,464 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The \( \chi^2 \) function

-
-
-

- -

-If we then introduce the matrix -$$ -\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, -$$ - -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) -$$ -\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} -$$ - -We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise) -$$ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -$$ - -resulting in -$$ -\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs022.html b/doc/src/Regression/._Regression-bs022.html deleted file mode 100644 index 968b64515..000000000 --- a/doc/src/Regression/._Regression-bs022.html +++ /dev/null @@ -1,457 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The \( \chi^2 \) function

-
-
-

-The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write -$$ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -$$ - -By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -$$ - -and -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs023.html b/doc/src/Regression/._Regression-bs023.html deleted file mode 100644 index 301726fe5..000000000 --- a/doc/src/Regression/._Regression-bs023.html +++ /dev/null @@ -1,491 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The \( \chi^2 \) function

-
-
-

- -

-For a linear fit (a first-order polynomial) we don't need to invert a matrix!! -Defining -$$ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -$$ - - -$$ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -$$ - - -$$ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -$$ - - -$$ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -$$ - - -$$ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -$$ - -

-we obtain - -$$ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -$$ - - -$$ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -$$ - -

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

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs024.html b/doc/src/Regression/._Regression-bs024.html deleted file mode 100644 index 2a1d4586f..000000000 --- a/doc/src/Regression/._Regression-bs024.html +++ /dev/null @@ -1,457 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Fitting an Equation of State for Dense Nuclear Matter

- -

-Before we continue, let us introduce yet another example. We are going to fit the -nuclear equation of state using results from many-body calculations. -The equation of state we have made available here, as function of -density, has been derived using modern nucleon-nucleon potentials with -the addition of three-body -forces. This -time the file is presented as a standard csv file. - -

-The beginning of the Python code here is similar to what you have seen before, -with the same initializations and declarations. We use also pandas -again, rather extensively in order to organize our data. - -

-The difference now is that we use Scikit-Learn's regression tools -instead of our own matrix inversion implementation. Furthermore, we -sneak in Ridge regression (to be discussed below) which includes a -hyperparameter \( \lambda \), also to be explained below. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs025.html b/doc/src/Regression/._Regression-bs025.html deleted file mode 100644 index 336b45fca..000000000 --- a/doc/src/Regression/._Regression-bs025.html +++ /dev/null @@ -1,535 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The code

- -

- - -

# Common imports
-import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-import matplotlib.pyplot as plt
-import sklearn.linear_model as skl
-from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as  csv file and organize the data into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-#  The design matrix now as function of various polytrops
-X = np.zeros((len(Density),4))
-X[:,3] = Density**(4.0/3.0)
-X[:,2] = Density
-X[:,1] = Density**(2.0/3.0)
-X[:,0] = 1
-
-# We use now Scikit-Learn's linear regressor and ridge regressor
-# OLS part
-clf = skl.LinearRegression().fit(X, Energies)
-ytilde = clf.predict(X)
-EoS['Eols']  = ytilde
-# The mean squared error                               
-print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
-# Explained variance score: 1 is perfect prediction                                 
-print('Variance score: %.2f' % r2_score(Energies, ytilde))
-# Mean absolute error                                                           
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
-print(clf.coef_, clf.intercept_)
-
-# The Ridge regression with a hyperparameter lambda = 0.1
-_lambda = 0.1
-clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
-yridge = clf_ridge.predict(X)
-EoS['Eridge']  = yridge
-# The mean squared error                               
-print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
-# Explained variance score: 1 is perfect prediction                                 
-print('Variance score: %.2f' % r2_score(Energies, yridge))
-# Mean absolute error                                                           
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
-print(clf_ridge.coef_, clf_ridge.intercept_)
-
-fig, ax = plt.subplots()
-ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
-ax.set_ylabel(r'Energy per particle')
-ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,
-            label='Theoretical data')
-ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
-            label='OLS')
-ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
-            label='Ridge $\lambda = 0.1$')
-ax.legend()
-save_fig("EoSfitting")
-plt.show()
-
-

-The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. Can you give an interpretation of the various powers of \( \rho \)? - -

-We note also that there is a small deviation between the -standard OLS and the Ridge regression at higher densities. We discuss this in more detail -below. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs026.html b/doc/src/Regression/._Regression-bs026.html deleted file mode 100644 index ca22d9f9b..000000000 --- a/doc/src/Regression/._Regression-bs026.html +++ /dev/null @@ -1,517 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Splitting our Data in Training and Test data

- -

-It is normal in essentially all Machine Learning studies to split the -data in a training set and a test set (sometimes also an additional -validation set). Scikit-Learn has an own function for this. There -is no explicit recipe for how much data should be included as training -data and say test data. An accepted rule of thumb is to use -approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will -postpone a discussion of this splitting to the end of these notes and -our discussion of the so-called bias-variance tradeoff. Here we -limit ourselves to repeat the above equation of state fitting example -but now splitting the data into a training set and a test set. - -

- - -

import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from sklearn.model_selection import train_test_split
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-def R2(y_data, y_model):
-    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
-def MSE(y_data,y_model):
-    n = np.size(y_model)
-    return np.sum((y_data-y_model)**2)/n
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as  csv file and organized into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-#  The design matrix now as function of various polytrops
-X = np.zeros((len(Density),5))
-X[:,0] = 1
-X[:,1] = Density**(2.0/3.0)
-X[:,2] = Density
-X[:,3] = Density**(4.0/3.0)
-X[:,4] = Density**(5.0/3.0)
-# We split the data in test and training data
-X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
-# matrix inversion to find beta
-beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
-# and then make the prediction
-ytilde = X_train @ beta
-print("Training R2")
-print(R2(y_train,ytilde))
-print("Training MSE")
-print(MSE(y_train,ytilde))
-ypredict = X_test @ beta
-print("Test R2")
-print(R2(y_test,ypredict))
-print("Test MSE")
-print(MSE(y_test,ypredict))
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs027.html b/doc/src/Regression/._Regression-bs027.html deleted file mode 100644 index 50e915fc9..000000000 --- a/doc/src/Regression/._Regression-bs027.html +++ /dev/null @@ -1,464 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The singular value decomposition

- -

-

-
-

- -

-The examples we have looked at so far are cases where we normally can -invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we -did both for the masses and the fitting of the equation of state, -leads to row vectors of the design matrix which are essentially -orthogonal due to the polynomial character of our model. This may -however not the be case in general and a standard matrix inversion -algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit -the coupling constant of the widely used Ising model. -There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. - -

-This is given by the Singular Value Decomposition algorithm, perhaps -the most powerful linear algebra algorithm. Let us look at a -different example where we may have problems with the standard matrix -inversion algorithm. Thereafter we dive into the math of the SVD. - -

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs028.html b/doc/src/Regression/._Regression-bs028.html deleted file mode 100644 index 39cfa7990..000000000 --- a/doc/src/Regression/._Regression-bs028.html +++ /dev/null @@ -1,489 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The Ising model

- -

-The one-dimensional Ising model with nearest neighbor interaction, no -external field and a constant coupling constant \( J \) is given by - -$$ -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\tag{1} -\end{align} -$$ - -

-where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins -in the system is determined by \( L \). For the one-dimensional system -there is no phase transition. - -

-We will look at a system of \( L = 40 \) spins with a coupling constant of -\( J = 1 \). To get enough training data we will generate 10000 states -with their respective energies. - -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from mpl_toolkits.axes_grid1 import make_axes_locatable
-import seaborn as sns
-import scipy.linalg as scl
-from sklearn.model_selection import train_test_split
-import tqdm
-sns.set(color_codes=True)
-cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
-
-L = 40
-n = int(1e4)
-
-spins = np.random.choice([-1, 1], size=(n, L))
-J = 1.0
-
-energies = np.zeros(n)
-
-for i in range(n):
-    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-
-

-Here we use ordinary least squares -regression to predict the energy for the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use linear regression to fit a value for -the coupling constant to achieve this. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs029.html b/doc/src/Regression/._Regression-bs029.html deleted file mode 100644 index 336d2cacf..000000000 --- a/doc/src/Regression/._Regression-bs029.html +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Reformulating the problem to suit regression

- -

-A more general form for the one-dimensional Ising model is - -$$ -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\tag{2} -\end{align} -$$ - -

-Here we allow for interactions beyond the nearest neighbors and a state dependent -coupling constant. This latter expression can be formulated as -a matrix-product -$$ -\begin{align} - \boldsymbol{H} = \boldsymbol{X} J, -\tag{3} -\end{align} -$$ - -

-where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the -elements \( -J_{jk} \). This form of writing the energy fits perfectly -with the form utilized in linear regression, that is - -$$ -\begin{align} - \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}, -\tag{4} -\end{align} -$$ - -

-We split the data in training and test data as discussed in the previous example - -

- - -

X = np.zeros((n, L ** 2))
-for i in range(n):
-    X[i] = np.outer(spins[i], spins[i]).ravel()
-y = energies
-X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs030.html b/doc/src/Regression/._Regression-bs030.html deleted file mode 100644 index 559929638..000000000 --- a/doc/src/Regression/._Regression-bs030.html +++ /dev/null @@ -1,480 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Linear regression

- -

-In the ordinary least squares method we choose the cost function - -$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}. -\tag{5} -\end{align} -$$ - -

-We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above. -This yields the expression for \( \boldsymbol{\beta} \) to be - -$$ - \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}}, -$$ - -

-which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist -an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an -intercept, i.e., a constant term, we must make sure that the -first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here - -

- - -

X_train_own = np.concatenate(
-    (np.ones(len(X_train))[:, np.newaxis], X_train),
-    axis=1
-)
-X_test_own = np.concatenate(
-    (np.ones(len(X_test))[:, np.newaxis], X_test),
-    axis=1
-)
-
-

- - -

def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
-    return scl.inv(x.T @ x) @ (x.T @ y)
-beta = ols_inv(X_train_own, y_train)
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs031.html b/doc/src/Regression/._Regression-bs031.html deleted file mode 100644 index 0a77e9794..000000000 --- a/doc/src/Regression/._Regression-bs031.html +++ /dev/null @@ -1,519 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Singular Value decomposition

- -

-Doing the inversion directly turns out to be a bad idea since the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular -value decomposition. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as - -$$ - \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y}, -$$ - -

-where the pseudoinverse of \( \boldsymbol{X} \) is given by - -$$ - \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}. -$$ - -

-Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \), -where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below). -where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for -\( \omega \) to -$$ -\begin{align} - \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}. -\tag{6} -\end{align} -$$ - -

-Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a -general matrix. Instead, doing \( QR \)-factorization and solving the -linear system as an equation would reduce this down to -\( \mathcal{O}(n^2) \) operations. - -

- - -

def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
-    u, s, v = scl.svd(x)
-    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
-
-

- - -

beta = ols_svd(X_train_own,y_train)
-
-

-When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here - -

- - -

J = beta[1:].reshape(L, L)
-
-

-A way of looking at the coefficients in \( J \) is to plot the matrices as images. - -

- - -

fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J, **cmap_args)
-plt.title("OLS", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-plt.show()
-
-

-It is interesting to note that OLS -considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as -valid matrix elements for \( J \). -In our discussion below on hyperparameters and Ridge and Lasso regression we will see that -this problem can be removed, partly and only with Lasso regression. - -

-In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs032.html b/doc/src/Regression/._Regression-bs032.html deleted file mode 100644 index e2d8e0601..000000000 --- a/doc/src/Regression/._Regression-bs032.html +++ /dev/null @@ -1,483 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Linear Regression Problems

- -

-One of the typical problems we encounter with linear regression, in particular -when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \) -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix -$$ -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} -$$ - -

-The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. - -

-Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{x} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -$$ -\begin{align*} -\boldsymbol{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -$$ - -We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. -This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs033.html b/doc/src/Regression/._Regression-bs033.html deleted file mode 100644 index 07e2b51a9..000000000 --- a/doc/src/Regression/._Regression-bs033.html +++ /dev/null @@ -1,460 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Fixing the singularity

- -

-If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem -$$ -\begin{align} -\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, -\tag{7} -\end{align} -$$ - -has linearly dependent column vectors, we will not be able to compute the inverse -of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \). -The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits. -This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters \( \beta_i \) cannot be estimated. - -

-A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change -$$ -\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, -$$ - -where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs034.html b/doc/src/Regression/._Regression-bs034.html deleted file mode 100644 index de4b3316b..000000000 --- a/doc/src/Regression/._Regression-bs034.html +++ /dev/null @@ -1,471 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Basic math of the SVD

- -

-From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is -a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \) -we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \). -The matrix has then a set of eigenpairs - -$$ -(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), -$$ - -and the eigenvalues are given by the diagonal matrix -$$ -\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). -$$ - -The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) -$$ -\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ - -with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \). - -

-Not all square matrices are diagonalizable. A matrix like the one discussed above -$$ -\boldsymbol{X} = \begin{bmatrix} -1& -1 \\ -1& -1\\ -\end{bmatrix} -$$ - -is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition -\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs035.html b/doc/src/Regression/._Regression-bs035.html deleted file mode 100644 index 12ca2541d..000000000 --- a/doc/src/Regression/._Regression-bs035.html +++ /dev/null @@ -1,463 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The SVD, a Fantastic Algorithm

- -

-However, and this is the strength of the SVD algorithm, any general -matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and -two orthogonal/unitary matrices. The Singular Value Decompostion -(SVD) theorem -states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in -terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( n\times n \) -and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has -dimensionality \( m \times m \) and the last dimensionality \( n\times n \). -We have then - -$$ -\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T -$$ - -

-As an example, the above defective matrix can be decomposed as - -$$ -\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ - -

-with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). -The SVD exits always! - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs036.html b/doc/src/Regression/._Regression-bs036.html deleted file mode 100644 index f0d68b336..000000000 --- a/doc/src/Regression/._Regression-bs036.html +++ /dev/null @@ -1,470 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Another Example

- -

-Consider the following matrix which can be SVD decomposed as - -$$ -\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. -$$ - -

-This is a \( 3\times 2 \) matrix which is decomposed in terms of a -\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see -that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?). - -

-And the SVD -decomposition (singular values) gives eigenvalues -\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), the -eigenvalues (singular values) are zero. - -

-In the general case, where our design matrix \( \boldsymbol{X} \) has dimension -\( n\times p \), the matrix is thus decomposed into an \( n\times n \) -orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) -and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) -singular values \( \sigma_i\lg 0 \) on the main diagonal and zeros filling -the rest of the matrix. There are at most \( p \) singular values -assuming that \( n > p \). In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have \( p > n \). These are often cases that lead to -near singular or singular matrices. - -

-The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs037.html b/doc/src/Regression/._Regression-bs037.html deleted file mode 100644 index 87e2a3326..000000000 --- a/doc/src/Regression/._Regression-bs037.html +++ /dev/null @@ -1,457 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Economy-size SVD

- -

-If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n -\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however -irrelevant in our calculations since they are multiplied with the -zeros in \( \boldsymbol{\Sigma} \). - -

-The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns -in either \( \boldsymbol{U} \) or \( \boldsymbol{V} \) that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. - -

-If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). -If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). -The \( n=p \) case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs038.html b/doc/src/Regression/._Regression-bs038.html deleted file mode 100644 index 882badd18..000000000 --- a/doc/src/Regression/._Regression-bs038.html +++ /dev/null @@ -1,484 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Mathematical Properties

- -

-There are several interesting mathematical properties which will be -relevant when we are going to discuss the differences between say -ordinary least squares (OLS) and Ridge regression. - -

-We have from OLS that the parameters of the linear approximation are given by -$$ -\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ - -

-The matrix to invert can be rewritten in terms of our SVD decomposition as - -$$ -\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. -$$ - -Using the orthogonality properties of \( \boldsymbol{U} \) we have - -$$ -\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T, -$$ - -with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared. - -

-This means that -$$ -(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D}, -$$ - -that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that -$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}, -$$ - -that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same. - -

-Going back to our OLS equation we have -$$ -\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. -$$ - -We will come back to this expression when we discuss Ridge regression. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs039.html b/doc/src/Regression/._Regression-bs039.html deleted file mode 100644 index b779e21a2..000000000 --- a/doc/src/Regression/._Regression-bs039.html +++ /dev/null @@ -1,490 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Ridge and LASSO Regression

- -

-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}\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 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}. -$$ - -

-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 - -$$ -{\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. -$$ - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs040.html b/doc/src/Regression/._Regression-bs040.html deleted file mode 100644 index 79442e146..000000000 --- a/doc/src/Regression/._Regression-bs040.html +++ /dev/null @@ -1,491 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

More on Ridge Regression

- -

-Using the matrix-vector expression for Ridge regression, - -$$ -C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta}, -$$ - -

-by 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 - -$$ -\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. - -

-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 -are rather interesting. - -

-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had -$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}. -$$ - -

-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as -$$ -\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} -$$ - -

-For Ridge regression this becomes - -$$ -\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\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} \). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs041.html b/doc/src/Regression/._Regression-bs041.html deleted file mode 100644 index 4f7064b9e..000000000 --- a/doc/src/Regression/._Regression-bs041.html +++ /dev/null @@ -1,456 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Interpreting the Ridge results

- -

-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} \). - -

-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. -Actually, calculating the variance of \( \boldsymbol{X}\boldsymbol{v}_j \) shows that this quantity is equal to \( \sigma_j^2/n \). -With a parameter \( \lambda \) we can thus shrink the role of specific parameters. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs042.html b/doc/src/Regression/._Regression-bs042.html deleted file mode 100644 index 0c995529e..000000000 --- a/doc/src/Regression/._Regression-bs042.html +++ /dev/null @@ -1,469 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

More interpretations

- -

-For the sake of simplicity, let us assume that the design matrix is orthonormal, that is - -$$ -\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. -$$ - -

-In this case the standard OLS results in -$$ -\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^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. - -

-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. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs043.html b/doc/src/Regression/._Regression-bs043.html deleted file mode 100644 index c44c78991..000000000 --- a/doc/src/Regression/._Regression-bs043.html +++ /dev/null @@ -1,449 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Where are we going?

- -

-Before we proceed, we need to rethink what we have been doing. In our -eager to fit the data, we have omitted several important elements in -our regression analysis. In what follows we will - -

    -
  1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
  2. -
  3. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
  4. -
- -This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs044.html b/doc/src/Regression/._Regression-bs044.html deleted file mode 100644 index fc2bf6ad7..000000000 --- a/doc/src/Regression/._Regression-bs044.html +++ /dev/null @@ -1,453 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Resampling methods

-
-
-

-Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs045.html b/doc/src/Regression/._Regression-bs045.html deleted file mode 100644 index 082121081..000000000 --- a/doc/src/Regression/._Regression-bs045.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Resampling approaches can be computationally expensive

-
-
-

- -

-Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. - -

-

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs046.html b/doc/src/Regression/._Regression-bs046.html deleted file mode 100644 index 77b3f2369..000000000 --- a/doc/src/Regression/._Regression-bs046.html +++ /dev/null @@ -1,449 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Why resampling methods ?

-
-
-

- -

    -
  • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
  • -
  • The results can be analysed with the same statistical tools as we would use analysing experimental data.
  • -
  • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
  • -
-
-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs047.html b/doc/src/Regression/._Regression-bs047.html deleted file mode 100644 index 927b9be13..000000000 --- a/doc/src/Regression/._Regression-bs047.html +++ /dev/null @@ -1,455 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistical analysis

-
-
-

- -

    -
  • As in other experiments, many numerical experiments have two classes of errors:
  • - -
      -
    • Statistical errors
    • -
    • Systematical errors
    • -
    - -
  • Statistical errors can be estimated using standard tools from statistics
  • -
  • Systematical errors are method specific and must be treated differently from case to case.
  • -
-
-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs048.html b/doc/src/Regression/._Regression-bs048.html deleted file mode 100644 index 6beabb135..000000000 --- a/doc/src/Regression/._Regression-bs048.html +++ /dev/null @@ -1,464 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics

-
-
-

-The probability distribution function (PDF) is a function -\( p(x) \) on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of \( X \) occur: -$$ -p(x) = \mathrm{prob}(X=x) -$$ - -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around \( x \) to be \( p(x)dx \). The continuous function \( p(x) \) then gives us -the density of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval \( [a,\,b] \) is then just the integral: -$$ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx -$$ - -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs049.html b/doc/src/Regression/._Regression-bs049.html deleted file mode 100644 index 70d02b6a2..000000000 --- a/doc/src/Regression/._Regression-bs049.html +++ /dev/null @@ -1,456 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, moments

-
-
-

-A particularly useful class of special expectation values are the -moments. The \( n \)-th moment of the PDF \( p \) is defined as -follows: -$$ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx -$$ - -The zero-th moment \( \langle 1\rangle \) is just the normalization condition of -\( p \). The first moment, \( \langle x\rangle \), is called the mean of \( p \) -and often denoted by the letter \( \mu \): -$$ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs050.html b/doc/src/Regression/._Regression-bs050.html deleted file mode 100644 index fd305b0a5..000000000 --- a/doc/src/Regression/._Regression-bs050.html +++ /dev/null @@ -1,471 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, central moments

-
-
-

-A special version of the moments is the set of central moments, -the n-th central moment defined as: -$$ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -$$ - -The zero-th and first central moments are both trivial, equal \( 1 \) and -\( 0 \), respectively. But the second central moment, known as the -variance of \( p \), is of particular interest. For the stochastic -variable \( X \), the variance is denoted as \( \sigma^2_X \) or \( \mathrm{var}(X) \): -$$ -\begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx -\tag{8}\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx -\tag{9}\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 -\tag{10}\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\tag{11} -\end{align} -$$ - -The square root of the variance, \( \sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle} \) is called the standard deviation of \( p \). It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the spread of \( p \) around its mean. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs051.html b/doc/src/Regression/._Regression-bs051.html deleted file mode 100644 index 1f7e91c6d..000000000 --- a/doc/src/Regression/._Regression-bs051.html +++ /dev/null @@ -1,464 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, covariance

-
-
-

-Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set \( \{X_i\} \) of \( n \) -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF \( P(x_1,\dots,x_n) \). The covariance of two -of the stochastic variables, \( X_i \) and \( X_j \), is defined as follows: -$$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\tag{12} -\end{align} -$$ - -with -$$ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs052.html b/doc/src/Regression/._Regression-bs052.html deleted file mode 100644 index bb072b2f6..000000000 --- a/doc/src/Regression/._Regression-bs052.html +++ /dev/null @@ -1,465 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, more covariance

-
-
-

-If we consider the above covariance as a matrix \( C_{ij}=\mathrm{cov}(X_i,\,X_j) \), then the diagonal elements are just the familiar -variances, \( C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i) \). It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables \( X_i \) and -\( X_j \), (\( i\neq j \)): -$$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\tag{13}\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle -\tag{14}\\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle -\tag{15}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle -\tag{16}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\tag{17} -\end{align} -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs053.html b/doc/src/Regression/._Regression-bs053.html deleted file mode 100644 index bb2d31a84..000000000 --- a/doc/src/Regression/._Regression-bs053.html +++ /dev/null @@ -1,459 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, independent variables

-
-
-

-If \( X_i \) and \( X_j \) are independent, we get -\( \langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle \), resulting in \( \mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j) \). - -

-Also useful for us is the covariance of linear combinations of -stochastic variables. Let \( \{X_i\} \) and \( \{Y_i\} \) be two sets of -stochastic variables. Let also \( \{a_i\} \) and \( \{b_i\} \) be two sets of -scalars. Consider the linear combination: -$$ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j -$$ - -By the linearity of the expectation value -$$ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs054.html b/doc/src/Regression/._Regression-bs054.html deleted file mode 100644 index 941746562..000000000 --- a/doc/src/Regression/._Regression-bs054.html +++ /dev/null @@ -1,465 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, more variance

-
-
-

-Now, since the variance is just \( \mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i) \), we get -the variance of the linear combination \( U = \sum_i a_i X_i \): -$$ -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\tag{18} -\end{equation} -$$ - -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -$$ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -$$ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -which will become very useful in our study of the error in the mean -value of a set of measurements. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs055.html b/doc/src/Regression/._Regression-bs055.html deleted file mode 100644 index beaf91621..000000000 --- a/doc/src/Regression/._Regression-bs055.html +++ /dev/null @@ -1,461 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics and stochastic processes

-
-
-

-A stochastic process is a process that produces sequentially a -chain of values: -$$ -\{x_1, x_2,\dots\,x_k,\dots\}. -$$ - -We will call these -values our measurements and the entire set as our measured -sample. The action of measuring all the elements of a sample -we will call a stochastic experiment since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF \( p_X^{\phantom X}(x) \), where \( X \) is just the formal symbol for the -stochastic variable whose PDF is \( p_X^{\phantom X}(x) \). Instead of -trying to determine the full distribution \( p \) we are often only -interested in finding the few lowest moments, like the mean -\( \mu_X^{\phantom X} \) and the variance \( \sigma_X^{\phantom X} \). -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs056.html b/doc/src/Regression/._Regression-bs056.html deleted file mode 100644 index 572f7309b..000000000 --- a/doc/src/Regression/._Regression-bs056.html +++ /dev/null @@ -1,459 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics and sample variables

-
-
-

-In practical situations a sample is always of finite size. Let that -size be \( n \). The expectation value of a sample, the sample mean, is then defined as follows: -$$ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -$$ - -The sample variance is: -$$ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -$$ - -its square root being the standard deviation of the sample. The -sample covariance is: -$$ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs057.html b/doc/src/Regression/._Regression-bs057.html deleted file mode 100644 index 48e567830..000000000 --- a/doc/src/Regression/._Regression-bs057.html +++ /dev/null @@ -1,454 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, sample variance and covariance

-
-
-

-Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq. (12) is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. - -

-These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean \( \mu_X \), variance \( \mathrm{var}(X) \) -and covariance \( \mathrm{cov}(X,Y) \). -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs058.html b/doc/src/Regression/._Regression-bs058.html deleted file mode 100644 index a0dc42c2a..000000000 --- a/doc/src/Regression/._Regression-bs058.html +++ /dev/null @@ -1,465 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, law of large numbers

-
-
-

-The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean \( \mu_X^{\phantom X} \) of the chosen PDF: -$$ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} -$$ - -The sample mean \( \bar{x}_n \) works therefore as an estimate of the true -mean \( \mu_X^{\phantom X} \). - -

-What we need to find out is how good an approximation \( \bar{x}_n \) is to -\( \mu_X^{\phantom X} \). In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the error of the sample mean, or -just sample error, and denote it by \( \mathrm{err}_X^{\phantom X} \). In -practice, we will only be able to produce an estimate of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs059.html b/doc/src/Regression/._Regression-bs059.html deleted file mode 100644 index 65d131b1d..000000000 --- a/doc/src/Regression/._Regression-bs059.html +++ /dev/null @@ -1,455 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, more on sample error

-
-
-

-Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements \( x_i \) -can be associated with its own stochastic variable \( X_i \). The -stochastic variable \( \overline X_n \) for the sample mean \( \bar{x}_n \) is -then just a linear combination, already familiar to us: -$$ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i -$$ - -All the coefficients are just equal \( 1/n \). The PDF of \( \overline X_n \), -denoted by \( p_{\overline X_n}(x) \) is the desired PDF of the sample -means. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs060.html b/doc/src/Regression/._Regression-bs060.html deleted file mode 100644 index af1206cdd..000000000 --- a/doc/src/Regression/._Regression-bs060.html +++ /dev/null @@ -1,454 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics

-
-
-

-The probability density of obtaining a sample mean \( \bar x_n \) -is the product of probabilities of obtaining arbitrary values \( x_1, -x_2,\dots,x_n \) with the constraint that the mean of the set \( \{x_i\} \) -is \( \bar x_n \): -$$ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 -$$ - -And in particular we are interested in its variance \( \mathrm{var}(\overline X_n) \). -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs061.html b/doc/src/Regression/._Regression-bs061.html deleted file mode 100644 index 201c00019..000000000 --- a/doc/src/Regression/._Regression-bs061.html +++ /dev/null @@ -1,458 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, central limit theorem

-
-
-

-It is generally not possible to express \( p_{\overline X_n}(x) \) in a -closed form given an arbitrary PDF \( p_X^{\phantom X} \) and a number -\( n \). But for the limit \( n\to\infty \) it is possible to make an -approximation. The very important result is called the central limit theorem. It tells us that as \( n \) goes to infinity, -\( p_{\overline X_n}(x) \) approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, \( \mu_{X}^{\phantom X} \) -and \( \sigma_{X}^{2} \), respectively: -$$ -\begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\tag{19} -\end{equation} -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs062.html b/doc/src/Regression/._Regression-bs062.html deleted file mode 100644 index d7f70e544..000000000 --- a/doc/src/Regression/._Regression-bs062.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, more technicalities

-
-
-

-The desired variance -\( \mathrm{var}(\overline X_n) \), i.e. the sample error squared -\( \mathrm{err}_X^2 \), is given by: -$$ -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\tag{20} -\end{equation} -$$ - -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -\( \mu_{X_i}^{\phantom X} \) of the stochastic variables \( X_i \). To -calculate these requires that we know the true multivariate PDF of all -the \( X_i \). But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the \( X_i \), estimating all properties of -\( X_i \) through the measurements of the sample. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs063.html b/doc/src/Regression/._Regression-bs063.html deleted file mode 100644 index 853fd1a25..000000000 --- a/doc/src/Regression/._Regression-bs063.html +++ /dev/null @@ -1,460 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics

-
-
-

-Our estimate of \( \mu_{X_i}^{\phantom X} \) is then the sample mean \( \bar x \) -itself, in accordance with the the central limit theorem: -$$ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x -$$ - -Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an -estimate of the covariance in Eq. (20) -$$ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, -$$ - -resulting in -$$ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs064.html b/doc/src/Regression/._Regression-bs064.html deleted file mode 100644 index 841a90caa..000000000 --- a/doc/src/Regression/._Regression-bs064.html +++ /dev/null @@ -1,472 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics and sample variance

-
-
-

-By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables \( X_i \) -$$ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, -$$ - -which is approximated as -$$ -\begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\tag{21} -\end{equation} -$$ - -

-Now we can calculate an estimate of the error -\( \mathrm{err}_X^{\phantom X} \) of the sample mean \( \bar x_n \): -$$ -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\tag{22} -\end{align} -$$ - -which is nothing but the sample covariance divided by the number of -measurements in the sample. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs065.html b/doc/src/Regression/._Regression-bs065.html deleted file mode 100644 index 08333bcdf..000000000 --- a/doc/src/Regression/._Regression-bs065.html +++ /dev/null @@ -1,468 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, uncorrelated results

-
-
-

- -

-In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables \( X_i \) are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: -$$ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), -$$ - -resulting in -$$ -\begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\tag{23} -\end{equation} -$$ - -where in the second step we have used Eq. (21). -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs066.html b/doc/src/Regression/._Regression-bs066.html deleted file mode 100644 index 6c7f7f24e..000000000 --- a/doc/src/Regression/._Regression-bs066.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, computations

-
-
-

-For computational purposes one usually splits up the estimate of -\( \mathrm{err}_X^2 \), given by Eq. (22), into two -parts -$$ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), -$$ - -which equals -$$ -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) -\tag{24} -\end{equation} -$$ - -The first term is the same as the error in the uncorrelated case, -Eq. (23). This means that the second -term accounts for the error correction due to correlation between the -measurements. For uncorrelated measurements this second term is zero. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs067.html b/doc/src/Regression/._Regression-bs067.html deleted file mode 100644 index 1f4897191..000000000 --- a/doc/src/Regression/._Regression-bs067.html +++ /dev/null @@ -1,455 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, more on computations of errors

-
-
-

-Computationally the uncorrelated first term is much easier to treat -efficiently than the second. -$$ -\mathrm{var}(x) = \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)^2 = -\left(\frac{1}{n}\sum_{k=1}^n x_k^2\right) - \bar x_n^2 -$$ - -We just accumulate separately the values \( x^2 \) and \( x \) for every -measurement \( x \) we receive. The correlation term, though, has to be -calculated at the end of the experiment since we need all the -measurements to calculate the cross terms. Therefore, all measurements -have to be stored throughout the experiment. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs068.html b/doc/src/Regression/._Regression-bs068.html deleted file mode 100644 index fed0a66ef..000000000 --- a/doc/src/Regression/._Regression-bs068.html +++ /dev/null @@ -1,466 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, wrapping up 1

-
-
-

-Let us analyze the problem by splitting up the correlation term into -partial sums of the form: -$$ -f_d = \frac{1}{n-d}\sum_{k=1}^{n-d}(x_k - \bar x_n)(x_{k+d} - \bar x_n) -$$ - -The correlation term of the error can now be rewritten in terms of -\( f_d \) -$$ -\frac{2}{n}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) = -2\sum_{d=1}^{n-1} f_d -$$ - -The value of \( f_d \) reflects the correlation between measurements -separated by the distance \( d \) in the sample samples. Notice that for -\( d=0 \), \( f \) is just the sample variance, \( \mathrm{var}(x) \). If we divide \( f_d \) -by \( \mathrm{var}(x) \), we arrive at the so called autocorrelation function -$$ -\kappa_d = \frac{f_d}{\mathrm{var}(x)} -$$ - -which gives us a useful measure of pairwise correlations -starting always at \( 1 \) for \( d=0 \). -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs069.html b/doc/src/Regression/._Regression-bs069.html deleted file mode 100644 index 67c484a91..000000000 --- a/doc/src/Regression/._Regression-bs069.html +++ /dev/null @@ -1,466 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, final expression

-
-
-

-The sample error (see eq. (24)) can now be -written in terms of the autocorrelation function: -$$ -\begin{align} -\mathrm{err}_X^2 &= -\frac{1}{n}\mathrm{var}(x)+\frac{2}{n}\cdot\mathrm{var}(x)\sum_{d=1}^{n-1} -\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=& -\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\ -&=\frac{\tau}{n}\cdot\mathrm{var}(x) -\tag{25} -\end{align} -$$ - -and we see that \( \mathrm{err}_X \) can be expressed in terms the -uncorrelated sample variance times a correction factor \( \tau \) which -accounts for the correlation between measurements. We call this -correction factor the autocorrelation time: -$$ -\begin{equation} -\tau = 1+2\sum_{d=1}^{n-1}\kappa_d -\tag{26} -\end{equation} -$$ -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs070.html b/doc/src/Regression/._Regression-bs070.html deleted file mode 100644 index b5cb2bae8..000000000 --- a/doc/src/Regression/._Regression-bs070.html +++ /dev/null @@ -1,458 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Statistics, effective number of correlations

-
-
-

-For a correlation free experiment, \( \tau \) -equals 1. From the point of view of -eq. (25) we can interpret a sequential -correlation as an effective reduction of the number of measurements by -a factor \( \tau \). The effective number of measurements becomes: -$$ -n_\mathrm{eff} = \frac{n}{\tau} -$$ - -To neglect the autocorrelation time \( \tau \) will always cause our -simple uncorrelated estimate of \( \mathrm{err}_X^2\approx \mathrm{var}(x)/n \) to -be less than the true sample error. The estimate of the error will be -too good. On the other hand, the calculation of the full -autocorrelation time poses an efficiency problem if the set of -measurements is very large. -

-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs071.html b/doc/src/Regression/._Regression-bs071.html deleted file mode 100644 index c8d786d91..000000000 --- a/doc/src/Regression/._Regression-bs071.html +++ /dev/null @@ -1,470 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Linking the regression analysis with a statistical interpretation

- -

-Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. -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. - -

-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 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 \). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs072.html b/doc/src/Regression/._Regression-bs072.html deleted file mode 100644 index ea9f32047..000000000 --- a/doc/src/Regression/._Regression-bs072.html +++ /dev/null @@ -1,452 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Assumptions made

- -

-The assumption we have made here can be summarized as (and this is going to 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 describes our data -$$ -\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}. -$$ - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs073.html b/doc/src/Regression/._Regression-bs073.html deleted file mode 100644 index f6c1a7d10..000000000 --- a/doc/src/Regression/._Regression-bs073.html +++ /dev/null @@ -1,467 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Expectation value and variance

- -

-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 -$$ -\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). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs074.html b/doc/src/Regression/._Regression-bs074.html deleted file mode 100644 index 0d34e7d64..000000000 --- a/doc/src/Regression/._Regression-bs074.html +++ /dev/null @@ -1,517 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

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

- -

-With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value -$$ -\mathbb{E}(\boldsymbol{\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}. -$$ - -This means that the estimator of the regression parameters is unbiased. - -

-We can also calculate the variance - -

-The variance of \( \boldsymbol{\beta} \) is -$$ -\begin{eqnarray*} -\mbox{Var}(\boldsymbol{\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: -\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{ -[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to -construct a confidence interval for the estimates. - -

-In a similar way, we cna obtain analytical expressions for say the -expectation values of the parameters \( \boldsymbol{\beta} \) and their variance -when we employ Ridge regression, and thereby 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 - -$$ -\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. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs075.html b/doc/src/Regression/._Regression-bs075.html deleted file mode 100644 index 63a117fc0..000000000 --- a/doc/src/Regression/._Regression-bs075.html +++ /dev/null @@ -1,466 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Cross-validation

- -

-Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e. the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. - -

-The setting of original and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the -training set, plays the role of original data on which the model is -built. The second of these data sets, called the test set, plays the -role of the novel data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of \( \lambda \) using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs076.html b/doc/src/Regression/._Regression-bs076.html deleted file mode 100644 index 1307d54da..000000000 --- a/doc/src/Regression/._Regression-bs076.html +++ /dev/null @@ -1,444 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Computationally expensive

- -

-The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: - -

- -

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs077.html b/doc/src/Regression/._Regression-bs077.html deleted file mode 100644 index f9822b325..000000000 --- a/doc/src/Regression/._Regression-bs077.html +++ /dev/null @@ -1,453 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Various steps in cross-validation

- -

-When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this \( k \)-fold cross-validation structures the data splitting. The -samples are divided into \( k \) more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the \( k \) subsets -involves a degree of randomness. This may be fully excluded when -choosing \( k=n \). This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs078.html b/doc/src/Regression/._Regression-bs078.html deleted file mode 100644 index bfe54afc5..000000000 --- a/doc/src/Regression/._Regression-bs078.html +++ /dev/null @@ -1,468 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

How to set up the cross-validation for Ridge and/or Lasso

- - - -$$ -\begin{align*} -\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} -\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} -\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} -\end{align*} -$$ - - - - -$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ - - - - -

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs079.html b/doc/src/Regression/._Regression-bs079.html deleted file mode 100644 index 79e1d53f1..000000000 --- a/doc/src/Regression/._Regression-bs079.html +++ /dev/null @@ -1,455 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Resampling methods: Jackknife and Bootstrap

- -

-Two famous -resampling methods are the independent bootstrap and the jackknife. - -

-The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as the dependent bootstrap. - -

-The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of \( \overline{X} \) (which often is the case), then there is no -need for bootstrapping. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs080.html b/doc/src/Regression/._Regression-bs080.html deleted file mode 100644 index efecd3647..000000000 --- a/doc/src/Regression/._Regression-bs080.html +++ /dev/null @@ -1,451 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Resampling methods: Jackknife

- -

-The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \boldsymbol{x}_i \) denote the vector -$$ -\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ - -

-which equals the vector \( \boldsymbol{x} \) with the exception that observation -number \( i \) is left out. Using this notation, define -\( \widehat{\theta}_i \) to be the estimator -\( \widehat{\theta} \) computed using \( \vec{X}_i \). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs081.html b/doc/src/Regression/._Regression-bs081.html deleted file mode 100644 index d69fce222..000000000 --- a/doc/src/Regression/._Regression-bs081.html +++ /dev/null @@ -1,468 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Jackknife code example

-

- - -

from numpy import *
-from numpy.random import randint, randn
-from time import time
-
-def jackknife(data, stat):
-    n = len(data);t = zeros(n); inds = arange(n); t0 = time()
-    ## 'jackknifing' by leaving out an observation for each i                                                                                                                      
-    for i in range(n):
-        t[i] = stat(delete(data,i) )
-
-    # analysis                                                                                                                                                                     
-    print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
-    print("original           bias      std. error")
-    print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
-
-    return t
-
-
-# Returns mean of data samples                                                                                                                                                     
-def stat(data):
-    return mean(data)
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# jackknife returns the data sample                                                                                                                                                
-t = jackknife(x, stat)
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs082.html b/doc/src/Regression/._Regression-bs082.html deleted file mode 100644 index 88c2e3683..000000000 --- a/doc/src/Regression/._Regression-bs082.html +++ /dev/null @@ -1,454 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Resampling methods: Bootstrap

-
-
-

-Bootstrapping is a nonparametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: - -

    -
  1. The bootstrap is quite general, although there are some cases in which it fails.
  2. -
  3. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
  4. -
  5. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
  6. -
  7. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
  8. -
-
-
- - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs083.html b/doc/src/Regression/._Regression-bs083.html deleted file mode 100644 index f13ff3412..000000000 --- a/doc/src/Regression/._Regression-bs083.html +++ /dev/null @@ -1,448 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Resampling methods: Bootstrap background

- -

-Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, -\( \widehat{\theta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to -estimate \( p(\boldsymbol{t}) \) by the relative frequency of -\( \widehat{\theta} \). You can think of this as using a histogram -in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely -resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point -estimators. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs084.html b/doc/src/Regression/._Regression-bs084.html deleted file mode 100644 index 563450133..000000000 --- a/doc/src/Regression/._Regression-bs084.html +++ /dev/null @@ -1,454 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Resampling methods: More Bootstrap background

- -

-In the case that \( \widehat{\theta} \) has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of \( X_i \), \( p(x) \), had been known, then it would have -been straight forward to do this by: - -

    -
  1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
  2. -
  3. Then using these numbers, we could compute a replica of \( \widehat{\theta} \) called \( \widehat{\theta}^* \).
  4. -
- -By repeated use of (1) and (2), many -estimates of \( \widehat{\theta} \) could have been obtained. The -idea is to use the relative frequency of \( \widehat{\theta}^* \) -(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs085.html b/doc/src/Regression/._Regression-bs085.html deleted file mode 100644 index ae9cc591e..000000000 --- a/doc/src/Regression/._Regression-bs085.html +++ /dev/null @@ -1,453 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Resampling methods: Bootstrap approach

- -

-But -unless there is enough information available about the process that -generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general -unknown. Therefore, Efron in 1979 asked the -question: What if we replace \( p(x) \) by the relative frequency -of the observation \( X_i \); if we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - -

-Instead of generating the histogram for the relative -frequency of the observation \( X_i \), just draw the values -\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector -\( \boldsymbol{X} \). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs086.html b/doc/src/Regression/._Regression-bs086.html deleted file mode 100644 index 784594eb9..000000000 --- a/doc/src/Regression/._Regression-bs086.html +++ /dev/null @@ -1,457 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Resampling methods: Bootstrap steps

- -

-The independent bootstrap works like this: - -

    -
  1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
  2. -
  3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
  4. -
  5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
  6. -
  7. Repeat this process \( k \) times.
  8. -
- -When you are done, you can draw a histogram of the relative frequency -of \( \widehat \theta^* \). This is your estimate of the probability -distribution \( p(t) \). Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of \( \widehat{\theta}^* \). Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of \( \widehat -\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values -\( \widehat \theta ^* \). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs087.html b/doc/src/Regression/._Regression-bs087.html deleted file mode 100644 index a2bb69c80..000000000 --- a/doc/src/Regression/._Regression-bs087.html +++ /dev/null @@ -1,496 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Code example for the Bootstrap method

- -

-The following code starts with a Gaussian distribution with mean value -\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data -used in the bootstrap analysis. The bootstrap analysis returns a data -set after a given number of bootstrap operations (as many as we have -data points). This data set consists of estimated mean values for each -bootstrap operation. The histogram generated by the bootstrap method -shows that the distribution for these mean values is also a Gaussian, -centered around the mean value \( \mu=100 \) but with standard deviation -\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in -this case the same as the number of original data points). The value -of the standard deviation is what we expect from the central limit -theorem. - -

- - -

from numpy import *
-from numpy.random import randint, randn
-from time import time
-import matplotlib.mlab as mlab
-import matplotlib.pyplot as plt
-
-# Returns mean of bootstrap samples                                                                                                                                                
-def stat(data):
-    return mean(data)
-
-# Bootstrap algorithm
-def bootstrap(data, statistic, R):
-    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
-    # non-parametric bootstrap         
-    for i in range(R):
-        t[i] = statistic(data[randint(0,n,n)])
-
-    # analysis    
-    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
-    print("original           bias      std. error")
-    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
-    return t
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# bootstrap returns the data sample                                    
-t = bootstrap(x, stat, datapoints)
-# the histogram of the bootstrapped  data                                                                                                    
-n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
-
-# add a 'best fit' line  
-y = mlab.normpdf( binsboot, mean(t), std(t))
-lt = plt.plot(binsboot, y, 'r--', linewidth=1)
-plt.xlabel('Smarts')
-plt.ylabel('Probability')
-plt.axis([99.5, 100.6, 0, 3.0])
-plt.grid(True)
-
-plt.show()
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs088.html b/doc/src/Regression/._Regression-bs088.html deleted file mode 100644 index 712697d73..000000000 --- a/doc/src/Regression/._Regression-bs088.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Code Example for Cross-validation and \( k \)-fold Cross-validation

- -

-The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.model_selection import KFold
-from sklearn.linear_model import Ridge
-from sklearn.model_selection import cross_val_score
-from sklearn.preprocessing import PolynomialFeatures
-
-# A seed just to ensure that the random numbers are the same for every run.
-# Useful for eventual debugging.
-np.random.seed(3155)
-
-# Generate the data.
-nsamples = 100
-x = np.random.randn(nsamples)
-y = 3*x**2 + np.random.randn(nsamples)
-
-## Cross-validation on Ridge regression using KFold only
-
-# Decide degree on polynomial to fit
-poly = PolynomialFeatures(degree = 6)
-
-# Decide which values of lambda to use
-nlambdas = 500
-lambdas = np.logspace(-3, 5, nlambdas)
-
-# Initialize a KFold instance
-k = 5
-kfold = KFold(n_splits = k)
-
-# Perform the cross-validation to estimate MSE
-scores_KFold = np.zeros((nlambdas, k))
-
-i = 0
-for lmb in lambdas:
-    ridge = Ridge(alpha = lmb)
-    j = 0
-    for train_inds, test_inds in kfold.split(x):
-        xtrain = x[train_inds]
-        ytrain = y[train_inds]
-
-        xtest = x[test_inds]
-        ytest = y[test_inds]
-
-        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
-        ridge.fit(Xtrain, ytrain[:, np.newaxis])
-
-        Xtest = poly.fit_transform(xtest[:, np.newaxis])
-        ypred = ridge.predict(Xtest)
-
-        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
-
-        j += 1
-    i += 1
-
-
-estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
-
-## Cross-validation using cross_val_score from sklearn along with KFold
-
-# kfold is an instance initialized above as:
-# kfold = KFold(n_splits = k)
-
-estimated_mse_sklearn = np.zeros(nlambdas)
-i = 0
-for lmb in lambdas:
-    ridge = Ridge(alpha = lmb)
-
-    X = poly.fit_transform(x[:, np.newaxis])
-    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
-
-    # cross_val_score return an array containing the estimated negative mse for every fold.
-    # we have to the the mean of every array in order to get an estimate of the mse of the model
-    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
-
-    i += 1
-
-## Plot and compare the slightly different ways to perform cross-validation
-
-plt.figure()
-
-plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
-plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
-
-plt.xlabel('log10(lambda)')
-plt.ylabel('mse')
-
-plt.legend()
-
-plt.show()
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs089.html b/doc/src/Regression/._Regression-bs089.html deleted file mode 100644 index 76d15ca46..000000000 --- a/doc/src/Regression/._Regression-bs089.html +++ /dev/null @@ -1,498 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The bias-variance tradeoff

- -

-We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset \( \mathcal{L} \) consisting of the data -\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). - -

-Let us assume that the true data is generated from a noisy model - -$$ -\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} -$$ - -

-where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). - -

-In our derivation of the ordinary least squares method we defined then -an approximation to the function \( f \) in terms of the parameters -\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, -that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). - -

-Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function -$$ -C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. -$$ - -

-We can rewrite this as -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2. -$$ - -

-The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error \( \boldsymbol{\epsilon} \). - -

-To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). -We use a more compact notation in terms of the expectation value -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], -$$ - -and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], -$$ - -which, using the abovementioned expectation values can be rewritten as -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, -$$ - -that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs090.html b/doc/src/Regression/._Regression-bs090.html deleted file mode 100644 index 4262a3a91..000000000 --- a/doc/src/Regression/._Regression-bs090.html +++ /dev/null @@ -1,492 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Example code for Bias-Variance tradeoff

-

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-
-np.random.seed(2018)
-
-n = 500
-n_boostraps = 100
-degree = 18  # A quite high value, just to show.
-noise = 0.1
-
-# Make data set.
-x = np.linspace(-1, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
-
-# Hold out some test data that is never used in training.
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-# Combine x transformation and model into one operation.
-# Not neccesary, but convenient.
-model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
-
-# The following (m x n_bootstraps) matrix holds the column vectors y_pred
-# for each bootstrap iteration.
-y_pred = np.empty((y_test.shape[0], n_boostraps))
-for i in range(n_boostraps):
-    x_, y_ = resample(x_train, y_train)
-
-    # Evaluate the new model on the same test data each time.
-    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
-# Note: Expectations and variances taken w.r.t. different training
-# data sets, hence the axis=1. Subsequent means are taken across the test data
-# set in order to obtain a total value, but before this we have error/bias/variance
-# calculated per data point in the test set.
-# Note 2: The use of keepdims=True is important in the calculation of bias as this 
-# maintains the column vector form. Dropping this yields very unexpected results.
-error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
-bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
-variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
-print('Error:', error)
-print('Bias^2:', bias)
-print('Var:', variance)
-print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
-
-plt.plot(x[::5, :], y[::5, :], label='f(x)')
-plt.scatter(x_test, y_test, label='Data points')
-plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
-plt.legend()
-plt.show()
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs091.html b/doc/src/Regression/._Regression-bs091.html deleted file mode 100644 index 900edcfc0..000000000 --- a/doc/src/Regression/._Regression-bs091.html +++ /dev/null @@ -1,483 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Understanding what happens

-

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-
-np.random.seed(2018)
-
-n = 40
-n_boostraps = 100
-maxdegree = 14
-
-
-# Make data set.
-x = np.linspace(-3, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
-error = np.zeros(maxdegree)
-bias = np.zeros(maxdegree)
-variance = np.zeros(maxdegree)
-polydegree = np.zeros(maxdegree)
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-for degree in range(maxdegree):
-    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
-    y_pred = np.empty((y_test.shape[0], n_boostraps))
-    for i in range(n_boostraps):
-        x_, y_ = resample(x_train, y_train)
-        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
-    polydegree[degree] = degree
-    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
-    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
-    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
-    print('Polynomial degree:', degree)
-    print('Error:', error[degree])
-    print('Bias^2:', bias[degree])
-    print('Var:', variance[degree])
-    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-
-plt.plot(polydegree, np.log10(error), label='Error')
-plt.plot(polydegree, bias, label='bias')
-plt.plot(polydegree, variance, label='Variance')
-plt.legend()
-plt.show()
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs092.html b/doc/src/Regression/._Regression-bs092.html deleted file mode 100644 index 15286cf43..000000000 --- a/doc/src/Regression/._Regression-bs092.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Summing up

- -

-The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - -

-The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below \( Var(\epsilon) \), the irreducible error. - -

-What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs093.html b/doc/src/Regression/._Regression-bs093.html deleted file mode 100644 index 96afec3c3..000000000 --- a/doc/src/Regression/._Regression-bs093.html +++ /dev/null @@ -1,506 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Another Example rom Scikit-Learn's Repository

-

- - -

"""
-============================
-Underfitting vs. Overfitting
-============================
-
-This example demonstrates the problems of underfitting and overfitting and
-how we can use linear regression with polynomial features to approximate
-nonlinear functions. The plot shows the function that we want to approximate,
-which is a part of the cosine function. In addition, the samples from the
-real function and the approximations of different models are displayed. The
-models have polynomial features of different degrees. We can see that a
-linear function (polynomial with degree 1) is not sufficient to fit the
-training samples. This is called **underfitting**. A polynomial of degree 4
-approximates the true function almost perfectly. However, for higher degrees
-the model will **overfit** the training data, i.e. it learns the noise of the
-training data.
-We evaluate quantitatively **overfitting** / **underfitting** by using
-cross-validation. We calculate the mean squared error (MSE) on the validation
-set, the higher, the less likely the model generalizes correctly from the
-training data.
-"""
-
-print(__doc__)
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.pipeline import Pipeline
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.linear_model import LinearRegression
-from sklearn.model_selection import cross_val_score
-
-
-def true_fun(X):
-    return np.cos(1.5 * np.pi * X)
-
-np.random.seed(0)
-
-n_samples = 30
-degrees = [1, 4, 15]
-
-X = np.sort(np.random.rand(n_samples))
-y = true_fun(X) + np.random.randn(n_samples) * 0.1
-
-plt.figure(figsize=(14, 5))
-for i in range(len(degrees)):
-    ax = plt.subplot(1, len(degrees), i + 1)
-    plt.setp(ax, xticks=(), yticks=())
-
-    polynomial_features = PolynomialFeatures(degree=degrees[i],
-                                             include_bias=False)
-    linear_regression = LinearRegression()
-    pipeline = Pipeline([("polynomial_features", polynomial_features),
-                         ("linear_regression", linear_regression)])
-    pipeline.fit(X[:, np.newaxis], y)
-
-    # Evaluate the models using crossvalidation
-    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
-                             scoring="neg_mean_squared_error", cv=10)
-
-    X_test = np.linspace(0, 1, 100)
-    plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
-    plt.plot(X_test, true_fun(X_test), label="True function")
-    plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
-    plt.xlabel("x")
-    plt.ylabel("y")
-    plt.xlim((0, 1))
-    plt.ylim((-2, 2))
-    plt.legend(loc="best")
-    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
-        degrees[i], -scores.mean(), scores.std()))
-plt.show()
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs094.html b/doc/src/Regression/._Regression-bs094.html deleted file mode 100644 index f84d240d0..000000000 --- a/doc/src/Regression/._Regression-bs094.html +++ /dev/null @@ -1,560 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

The one-dimensional Ising model

- -

-Let us bring back the Ising model again, but now with an additional -focus on Ridge and Lasso regression as well. We repeat some of the -basic parts of the Ising model and the setup of the training and test -data. The one-dimensional Ising model with nearest neighbor -interaction, no external field and a constant coupling constant \( J \) is -given by - -$$ -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\tag{27} -\end{align} -$$ - -where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins in the system is determined by \( L \). For the one-dimensional system there is no phase transition. - -

-We will look at a system of \( L = 40 \) spins with a coupling constant of \( J = 1 \). To get enough training data we will generate 10000 states with their respective energies. - -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from mpl_toolkits.axes_grid1 import make_axes_locatable
-import seaborn as sns
-import scipy.linalg as scl
-from sklearn.model_selection import train_test_split
-import sklearn.linear_model as skl
-import tqdm
-sns.set(color_codes=True)
-cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
-
-L = 40
-n = int(1e4)
-
-spins = np.random.choice([-1, 1], size=(n, L))
-J = 1.0
-
-energies = np.zeros(n)
-
-for i in range(n):
-    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-
-

-A more general form for the one-dimensional Ising model is - -$$ -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\tag{28} -\end{align} -$$ - -

-Here we allow for interactions beyond the nearest neighbors and a more -adaptive coupling matrix. This latter expression can be formulated as -a matrix-product on the form -$$ -\begin{align} - H = X J, -\tag{29} -\end{align} -$$ - -

-where \( X_{jk} = s_j s_k \) and \( J \) is the matrix consisting of the -elements \( -J_{jk} \). This form of writing the energy fits perfectly -with the form utilized in linear regression, viz. -$$ -\begin{align} - \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}. -\tag{30} -\end{align} -$$ - -We organize the data as we did above -

- - -

X = np.zeros((n, L ** 2))
-for i in range(n):
-    X[i] = np.outer(spins[i], spins[i]).ravel()
-y = energies
-X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)
-
-X_train_own = np.concatenate(
-    (np.ones(len(X_train))[:, np.newaxis], X_train),
-    axis=1
-)
-
-X_test_own = np.concatenate(
-    (np.ones(len(X_test))[:, np.newaxis], X_test),
-    axis=1
-)
-
-

-We will do all fitting with Scikit-Learn, - -

- - -

clf = skl.LinearRegression().fit(X_train, y_train)
-
-

-When extracting the \( J \)-matrix we make sure to remove the intercept -

- - -

J_sk = clf.coef_.reshape(L, L)
-
-

-And then we plot the results -

- - -

fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_sk, **cmap_args)
-plt.title("LinearRegression from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-plt.show()
-
-

-The results perfectly with our previous discussion where we used our own code. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs095.html b/doc/src/Regression/._Regression-bs095.html deleted file mode 100644 index 51156d4a3..000000000 --- a/doc/src/Regression/._Regression-bs095.html +++ /dev/null @@ -1,460 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Ridge regression

- -

-Having explored the ordinary least squares we move on to ridge -regression. In ridge regression we include a regularizer. This -involves a new cost function which leads to a new estimate for the -weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The -cost function is given by - -$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}. -\tag{31} -\end{align} -$$ - -

- - -

_lambda = 0.1
-clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
-J_ridge_sk = clf_ridge.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_ridge_sk, **cmap_args)
-plt.title("Ridge from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-plt.show()
-
-

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs096.html b/doc/src/Regression/._Regression-bs096.html deleted file mode 100644 index 9b8d9e10e..000000000 --- a/doc/src/Regression/._Regression-bs096.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

LASSO regression

- -

-In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function. - -$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}. -\tag{32} -\end{align} -$$ - -

-Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn. - -

- - -

clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)
-J_lasso_sk = clf_lasso.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_lasso_sk, **cmap_args)
-plt.title("Lasso from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-plt.show()
-
-

-It is quite striking how LASSO breaks the symmetry of the coupling -constant as opposed to ridge and OLS. We get a sparse solution with -\( J_{j, j + 1} = -1 \). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs097.html b/doc/src/Regression/._Regression-bs097.html deleted file mode 100644 index 9399d436b..000000000 --- a/doc/src/Regression/._Regression-bs097.html +++ /dev/null @@ -1,477 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Performance as function of the regularization parameter

- -

-We see how the different models perform for a different set of values for \( \lambda \). - -

- - -

lambdas = np.logspace(-4, 5, 10)
-
-train_errors = {
-    "ols_sk": np.zeros(lambdas.size),
-    "ridge_sk": np.zeros(lambdas.size),
-    "lasso_sk": np.zeros(lambdas.size)
-}
-
-test_errors = {
-    "ols_sk": np.zeros(lambdas.size),
-    "ridge_sk": np.zeros(lambdas.size),
-    "lasso_sk": np.zeros(lambdas.size)
-}
-
-plot_counter = 1
-
-fig = plt.figure(figsize=(32, 54))
-
-for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
-    for key, method in zip(
-        ["ols_sk", "ridge_sk", "lasso_sk"],
-        [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
-    ):
-        method = method.fit(X_train, y_train)
-
-        train_errors[key][i] = method.score(X_train, y_train)
-        test_errors[key][i] = method.score(X_test, y_test)
-
-        omega = method.coef_.reshape(L, L)
-
-        plt.subplot(10, 5, plot_counter)
-        plt.imshow(omega, **cmap_args)
-        plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda))
-        plot_counter += 1
-
-plt.show()
-
-

-We see that LASSO reaches a good solution for low -values of \( \lambda \), but will "wither" when we increase \( \lambda \) too -much. Ridge is more stable over a larger range of values for -\( \lambda \), but eventually also fades away. - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs098.html b/doc/src/Regression/._Regression-bs098.html deleted file mode 100644 index 205ff2efa..000000000 --- a/doc/src/Regression/._Regression-bs098.html +++ /dev/null @@ -1,474 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Finding the optimal value of \( \lambda \)

- -

-To determine which value of \( \lambda \) is best we plot the accuracy of -the models when predicting the training and the testing set. We expect -the accuracy of the training set to be quite good, but if the accuracy -of the testing set is much lower this tells us that we might be -subject to an overfit model. The ideal scenario is an accuracy on the -testing set that is close to the accuracy of the training set. - -

- - -

fig = plt.figure(figsize=(20, 14))
-
-colors = {
-    "ols_sk": "r",
-    "ridge_sk": "y",
-    "lasso_sk": "c"
-}
-
-for key in train_errors:
-    plt.semilogx(
-        lambdas,
-        train_errors[key],
-        colors[key],
-        label="Train {0}".format(key),
-        linewidth=4.0
-    )
-
-for key in test_errors:
-    plt.semilogx(
-        lambdas,
-        test_errors[key],
-        colors[key] + "--",
-        label="Test {0}".format(key),
-        linewidth=4.0
-    )
-plt.legend(loc="best", fontsize=18)
-plt.xlabel(r"$\lambda$", fontsize=18)
-plt.ylabel(r"$R^2$", fontsize=18)
-plt.tick_params(labelsize=18)
-plt.show()
-
-

-From the above figure we can see that LASSO with \( \lambda = 10^{-2} \) -achieves a very good accuracy on the test set. This by far surpasses the -other models for all values of \( \lambda \). - -

-

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/._Regression-bs099.html b/doc/src/Regression/._Regression-bs099.html deleted file mode 100644 index 89e30924b..000000000 --- a/doc/src/Regression/._Regression-bs099.html +++ /dev/null @@ -1,650 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - -

Further Exercises

- -

Exercise 1

- -

-We will 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,1)
-y = 5*x*x+0.1*np.random.randn(100,1)
-
-
    -
  1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial.
  2. -
  3. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
  4. -
  5. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  6. -
- -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -

-You can use the functionality included in scikit-learn. If you feel -for it, you can use your own program and define functions which -compute the above two functions. Discuss the meaning of these -results. Try also to vary the coefficient in front of the added -stochastic noise term and discuss the quality of the fits. - -

Exercise 2, variance of the parameters \( \beta \) in linear regression

- -

-Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as - -$$ -\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, -$$ - -with -$$ -\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, -$$ - -where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)). - -

Exercise 3

- -

-This exercise is a continuation of exercise 1. 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. You can use the code under the Regression as an example on how to use the Ridge and the Lasso 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,1)
-y = 5*x*x+0.1*np.random.randn(100,1)
-
-
    -
  1. Write your own code for the Ridge method and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 1. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
  2. -
  3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
  4. -
  5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing 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 that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions
  6. -
  7. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.
  8. -
  9. Try to implement the cross-validation as well.
  10. -
  11. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  12. -
- -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. - -

Exercise 4

- -

-We will study how -to fit polynomials to a specific two-dimensional function called -Franke's -function. This -is a function which has been widely used when testing various interpolation and fitting -algorithms. Furthermore, after having established the model and the -method, we will employ resamling techniques such as the cross-validation and/or -the bootstrap methods, in order to perform a proper assessment of our models. - -

-The Franke function, which is a weighted sum of four exponentials reads as follows -$$ -\begin{align*} -f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ -&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. -\end{align*} -$$ - -

-The function will be defined for \( x,y\in [0,1] \). Our first step will -be to perform an OLS regression analysis of this function, trying out -a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y, -x^2, y^2, xy, \dots] \). We will also include cross-validation and -bootstrap as resampling techniques. As in homeworks 1 and 2, we -can use a uniform distribution to set up the arrays of values for \( x \) -and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size. -In this case we will have two predictors and need to fit a -function (for example a polynomial) of \( x \) and \( y \). Thereafter we will -repeat much of the same procedure using the the Ridge and -Lasso regression methods, introducing thus a dependence on the bias -(penalty) \( \lambda \). - -

-The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) -

- - -

from mpl_toolkits.mplot3d import Axes3D
-import matplotlib.pyplot as plt
-from matplotlib import cm
-from matplotlib.ticker import LinearLocator, FormatStrFormatter
-import numpy as np
-from random import random, seed
-
-fig = plt.figure()
-ax = fig.gca(projection='3d')
-
-# Make data.
-x = np.arange(0, 1, 0.05)
-y = np.arange(0, 1, 0.05)
-x, y = np.meshgrid(x,y)
-
-
-def FrankeFunction(x,y):
-    term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-    term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-    term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-    term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-    return term1 + term2 + term3 + term4
-
-
-z = FrankeFunction(x, y)
-
-# Plot the surface.
-surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
-                       linewidth=0, antialiased=False)
-
-# Customize the z axis.
-ax.set_zlim(-0.10, 1.40)
-ax.zaxis.set_major_locator(LinearLocator(10))
-ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
-
-# Add a color bar which maps values to colors.
-fig.colorbar(surf, shrink=0.5, aspect=5)
-
-plt.show()
-
-

-We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where -\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform -distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition -an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). - -

-Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3 -and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -

-Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm -and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models. - -

-Write then your own code for the Ridge method, either using matrix -inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the -previous exercise (for the same polynomials and include resampling -techniques) but now for different values of \( \lambda \). Compare and -analyze your results with those obtained with standard OLS. Study the -dependence on \( \lambda \) while also varying eventually the strength of -the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). - -

-Then perform the same studies but now with Lasso regression. Use the functionalities of -scikit-learn. Give a critical discussion of the three methods and a -judgement of which model fits the data best. - -

- -

- - -
- - - - - - - -
- -
- - - - - - diff --git a/doc/src/Regression/README.txt b/doc/src/Regression/README.txt deleted file mode 100644 index f3bf58066..000000000 --- a/doc/src/Regression/README.txt +++ /dev/null @@ -1,2 +0,0 @@ -This IPython notebook Regression.ipynb does not require any additional -programs. diff --git a/doc/src/Regression/Regression-bs.html b/doc/src/Regression/Regression-bs.html deleted file mode 100644 index aef0fd910..000000000 --- a/doc/src/Regression/Regression-bs.html +++ /dev/null @@ -1,452 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - - - -
-

Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis

- -

- - -

-Morten Hjorth-Jensen [1, 2] -
- -

- - -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

-

Jul 22, 2019

-
-

- - -

Read »

- - -
- -

- -

- - -
- - - - - - - -
- © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - - - - diff --git a/doc/src/Regression/Regression-minted.pdf b/doc/src/Regression/Regression-minted.pdf deleted file mode 100644 index 33108d9e9..000000000 Binary files a/doc/src/Regression/Regression-minted.pdf and /dev/null differ diff --git a/doc/src/Regression/Regression-plain-minted.tex b/doc/src/Regression/Regression-plain-minted.tex deleted file mode 100644 index 35dc47bdb..000000000 --- a/doc/src/Regression/Regression-plain-minted.tex +++ /dev/null @@ -1,3673 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% - - -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{fancyvrb} % packages needed for verbatim environments -\usepackage{minted} -\usemintedstyle{default} - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -\usepackage[framemethod=TikZ]{mdframed} - -% --- begin definitions of admonition environments --- - -% --- end of definitions of admonition environments --- - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Jul 22, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection*{Why Linear Regression (aka Ordinary Least Squares and family)} - -Fitting a continuous function with linear parameterization in terms of the parameters $\bm{\beta}$. -\begin{itemize} -\item Method of choice for fitting a continuous function! - -\item Gives an excellent introduction to central Machine Learning features with \textbf{understandable pedagogical} links to other methods like \textbf{Neural Networks}, \textbf{Support Vector Machines} etc - -\item Analytical expression for the fitting parameters $\bm{\beta}$ - -\item Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more - -\item Analytical relation with probabilistic interpretations - -\item Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics - -\item Easy to code! And links well with classification problems and logistic regression and neural networks - -\item Allows for \textbf{easy} hands-on understanding of gradient descent methods - -\item and many more features -\end{itemize} - -\noindent -For more discussions of Ridge and Lasso regression, \href{{https://arxiv.org/abs/1509.09169}}{Wessel van Wieringen's} article is highly recommended. -Similarly, \href{{https://arxiv.org/abs/1803.08823}}{Mehta et al's article} is also recommended. - - -% !split -\subsection*{Regression analysis, overarching aims} - -% --- begin paragraph admon --- -\paragraph{} - -Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\bm{x} =[x_0, x_1,\dots, x_{n-1}]^T$. -The first variable is called the \textbf{dependent}, the \textbf{outcome} or the \textbf{response} variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable. - -A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$, that is the conditional distribution for $\bm{y}$ with a given $\bm{x}$. The estimation of $p(\bm{y}\vert \bm{x})$ is made using a data set with -\begin{itemize} -\item $n$ cases $i = 0, 1, 2, \dots, n-1$ - -\item Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ - -\item $p$ so-called explanatory (independent or predictor) variables $\bm{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}]$ with $i = 0, 1, 2, \dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. -\end{itemize} - -\noindent - The goal of the regression analysis is to extract/exploit relationship between $\bm{y}$ and $\bm{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. -% --- end paragraph admon --- - - - -% !split -\subsection*{Regression analysis, overarching aims II} - -% --- begin paragraph admon --- -\paragraph{} - - -Consider an experiment in which $p$ characteristics of $n$ samples are -measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix -$\mathbf{X}$. - -The matrix $\mathbf{X}$ is called the \emph{design -matrix}. Additional information of the samples is available in the -form of $\bm{y}$ (also as above). The variable $\bm{y}$ is -generally referred to as the \emph{response variable}. The aim of -regression analysis is to explain $\bm{y}$ in terms of -$\bm{X}$ through a functional relationship like $y_i = -f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of -$f(\cdot)$ is available, it is common to assume a linear relationship -between $\bm{X}$ and $\bm{y}$. This assumption gives rise to -the \emph{linear regression model} where $\bm{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T}$ are the \emph{regression parameters}. - -Linear regression gives us a set of analytical equations for the parameters $\beta_j$. -% --- end paragraph admon --- - - - - - -% !split -\subsection*{Examples} - -% --- begin paragraph admon --- -\paragraph{} -In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$, -consider the model we discussed for describing nuclear binding energies. - -There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. -Assuming -\[ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, -\] -we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms. -This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a -$p\times n$ matrix $\bm{X}$. - -Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called \href{{https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub}}{credit card default data from Taiwan}. The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \times 30000$ -% --- end paragraph admon --- - - - - - - - -% !split -\subsection*{General linear models} - -% --- begin paragraph admon --- -\paragraph{} -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\bm{y}=[y_0,y_1,\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\bm{x}=[x_0,x_1,\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. - -Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is -\[ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, -\] -where $\epsilon_i$ is the error in our approximation. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Rewriting the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} -For every set of values $y_i,x_i$ we have thus the corresponding set of equations -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -% --- end paragraph admon --- - - - - -% !split -\subsection*{Rewriting the fitting procedure as a linear algebra problem, more details} - -% --- begin paragraph admon --- -\paragraph{} -Defining the vectors -\[ -\bm{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -\] -and -\[ -\bm{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -\] -and -\[ -\bm{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -\] -and the design matrix -\[ -\bm{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -\] -we can rewrite our equations as -\[ -\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. -\] -The above design matrix is called a \href{{https://en.wikipedia.org/wiki/Vandermonde_matrix}}{Vandermonde matrix}. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Generalizing the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} - -We are obviously not limited to the above polynomial expansions. We -could replace the various powers of $x$ with elements of Fourier -series or instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j -x_i)}$, or time series or other orthogonal functions. For every set -of values $y_i,x_i$ we can then generalize the equations to - -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} - -\textbf{Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!} -% --- end paragraph admon --- - - - - -% !split -\subsection*{Generalizing the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} -We redefine in turn the matrix $\bm{X}$ as -\[ -\bm{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -\] -and without loss of generality we rewrite again our equations as -\[ -\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. -\] -The left-hand side of this equation is kwown. Our error vector $\bm{\epsilon}$ and the parameter vector $\bm{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? -% --- end paragraph admon --- - - - - -% !split -\subsection*{Optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -We have defined the matrix $\bm{X}$ via the equations -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} - -As we noted above, we stayed with a system with the design matrix - $\bm{X}\in {\mathbb{R}}^{n\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define -our matrix as $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Our model for the nuclear binding energies} - -In our \href{{https://compphysics.github.io/MachineLearningMSU/doc/pub/Introduction/html/Introduction.html}}{introductory notes} we looked at the so-called \href{{https://en.wikipedia.org/wiki/Semi-empirical_mass_formula}}{liguid drop model}. Let us remind ourselves about what we did by looking at the code. - -We restate the parts of the code we are most interested in. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from IPython.display import display -import os - -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("MassEval2016.dat"),'r') - - -# Read the experimental data with Pandas -Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), - names=('N', 'Z', 'A', 'Element', 'Ebinding'), - widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), - header=39, - index_col=False) - -# Extrapolated values are indicated by '#' in place of the decimal place, so -# the Ebinding column won't be numeric. Coerce to float and drop these entries. -Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') -Masses = Masses.dropna() -# Convert from keV to MeV. -Masses['Ebinding'] /= 1000 - -# Group the DataFrame by nucleon number, A. -Masses = Masses.groupby('A') -# Find the rows of the grouped DataFrame with the maximum binding energy. -Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) -A = Masses['A'] -Z = Masses['Z'] -N = Masses['N'] -Element = Masses['Element'] -Energies = Masses['Ebinding'] - -# Now we set up the design matrix X -X = np.zeros((len(A),5)) -X[:,0] = 1 -X[:,1] = A -X[:,2] = A**(2.0/3.0) -X[:,3] = A**(-1.0/3.0) -X[:,4] = A**(-1.0) -# Then nice printout using pandas -DesignMatrix = pd.DataFrame(X) -DesignMatrix.index = A -DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A'] -display(DesignMatrix) -\end{minted} - -With $\bm{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as -\[ -\bm{\tilde{y}}= \bm{X}\bm{\beta}, -\] -throughout these lectures. - - -% !split -\subsection*{Optimizing our parameters, more details} - -% --- begin paragraph admon --- -\paragraph{} -With the above we use the design matrix to define the approximation $\bm{\tilde{y}}$ via the unknown quantity $\bm{\beta}$ as -\[ -\bm{\tilde{y}}= \bm{X}\bm{\beta}, -\] -and in order to find the optimal parameters $\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parameterized values $\tilde{y}_i$, namely -\[ -C(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, -\] -or using the matrix $\bm{X}$ and in a more compact matrix-vector notation as -\[ -C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}^T\bm{\beta}\right)^T\left(\bm{y}-\bm{X}^T\bm{\beta}\right)\right\}. -\] -This function is one possible way to define the so-called cost function. - - - -It is also common to define -the function $Q$ as - -\[ -C(\bm{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, -\] -since when taking the first derivative with respect to the unknown parameters $\beta$, the factor of $2$ cancels out. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} - -The function -\[ -C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}, -\] -can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises) -\[ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -\] - -where $\langle y_i \rangle$ is the mean value. Keep in mind also that -till now we have treated $y_i$ as the exact value. Normally, the -response (dependent or outcome) variable $y_i$ the outcome of a -numerical experiment or another type of experiment and is thus only an -approximation to the true value. It is then always accompanied by an -error estimate, often limited to a statistical error estimate given by -the standard deviation discussed earlier. In the discussion here we -will treat $y_i$ as our exact value for the response variable. - -In order to find the parameters $\beta_i$ we will then minimize the spread of $C(\bm{\beta})$, that is we are going to solve the problem -\[ -{\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\}. -\] -In practical terms it means we will require -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -\] -which results in -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -\] -or in a matrix-vector form as -\[ -\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right). -\] -% --- end paragraph admon --- - - - - -% !split -\subsection*{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -We can rewrite -\[ -\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right), -\] -as -\[ -\bm{X}^T\bm{y} = \bm{X}^T\bm{X}\bm{\beta}, -\] -and if the matrix $\bm{X}^T\bm{X}$ is invertible we have the solution -\[ -\bm{\beta} =\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] - -We note also that since our design matrix is defined as $\bm{X}\in -{\mathbb{R}}^{n\times p}$, the product $\bm{X}^T\bm{X} \in -{\mathbb{R}}^{p\times p}$. In the above case we have that $p \ll n$, -in our case $p=5$ meaning that we end up with inverting a small -$5\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional -matrices to invert. The methods discussed here and for many other -supervised learning algorithms like classification with logistic -regression or support vector machines, exhibit dimensionalities which -allow for the usage of direct linear algebra methods such as \textbf{LU} decomposition or \textbf{Singular Value Decomposition} (SVD) for finding the inverse of the matrix -$\bm{X}^T\bm{X}$. -% --- end paragraph admon --- - - - -% !split -\subsection*{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -The residuals $\bm{\epsilon}$ are in turn given by -\[ -\bm{\epsilon} = \bm{y}-\bm{\tilde{y}} = \bm{y}-\bm{X}\bm{\beta}, -\] -and with -\[ -\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, -\] -we have -\[ -\bm{X}^T\bm{\epsilon}=\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, -\] -meaning that the solution for $\bm{\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. -% --- end paragraph admon --- - - - - -Let us now return to our nuclear binding energies and simply code the above equations. - -% !split -\subsection*{Own code for Ordinary Least Squares} - -It is rather straightforward to implement the matrix inversion and obtain the parameters $\bm{\beta}$. After having defined the matrix $\bm{X}$ we simply need to -write -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# matrix inversion to find beta -beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies) -# and then make the prediction -ytilde = X @ beta -\end{minted} -Alternatively, you can use the least squares functionality in \textbf{Numpy} as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fit = np.linalg.lstsq(X, Energies, rcond =None)[0] -ytildenp = np.dot(fit,X.T) -\end{minted} - -And finally we plot our fit with and compare with data -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -Masses['Eapprox'] = ytilde -# Generate a plot comparing the experimental with the fitted values values. -fig, ax = plt.subplots() -ax.set_xlabel(r'$A = N + Z$') -ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') -ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, - label='Ame2016') -ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', - label='Fit') -ax.legend() -save_fig("Masses2016OLS") -plt.show() -\end{minted} - -% !split -\subsection*{Adding error analysis and training set up} - -We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. -Since we are not using _Scikit-Learn here we can define our own $R2$ function as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) -\end{minted} -and we would be using it as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -print(R2(Energies,ytilde)) -\end{minted} - -We can easily add our \textbf{MSE} score as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -print(MSE(Energies,ytilde)) -\end{minted} -and finally the relative error as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def RelativeError(y_data,y_model): - return abs((y_data-y_model)/y_data) -print(RelativeError(Energies, ytilde)) -\end{minted} - - - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -Normally, the response (dependent or outcome) variable $y_i$ is the -outcome of a numerical experiment or another type of experiment and is -thus only an approximation to the true value. It is then always -accompanied by an error estimate, often limited to a statistical error -estimate given by the standard deviation discussed earlier. In the -discussion here we will treat $y_i$ as our exact value for the -response variable. - -Introducing the standard deviation $\sigma_i$ for each measurement -$y_i$, we define now the $\chi^2$ function (omitting the $1/n$ term) -as - -\[ -\chi^2(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\frac{1}{\bm{\Sigma^2}}\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, -\] -where the matrix $\bm{\Sigma}$ is a diagonal matrix with $\sigma_i$ as matrix elements. -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -In order to find the parameters $\beta_i$ we will then minimize the spread of $\chi^2(\bm{\beta})$ by requiring -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -\] -which results in -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -\] -or in a matrix-vector form as -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right). -\] -where we have defined the matrix $\bm{A} =\bm{X}/\bm{\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\sigma_i$ and the vector $\bm{b}$ with elements $b_i = y_i/\sigma_i$. -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -We can rewrite -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right), -\] -as -\[ -\bm{A}^T\bm{b} = \bm{A}^T\bm{A}\bm{\beta}, -\] -and if the matrix $\bm{A}^T\bm{A}$ is invertible we have the solution -\[ -\bm{\beta} =\left(\bm{A}^T\bm{A}\right)^{-1}\bm{A}^T\bm{b}. -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -If we then introduce the matrix -\[ -\bm{H} = \left(\bm{A}^T\bm{A}\right)^{-1}, -\] -we have then the following expression for the parameters $\beta_j$ (the matrix elements of $\bm{H}$ are $h_{ij}$) -\[ -\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} -\] -We state without proof the expression for the uncertainty in the parameters $\beta_j$ as (we leave this as an exercise) -\[ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -\] -resulting in -\[ -\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} -The first step here is to approximate the function $y$ with a first-order polynomial, that is we write -\[ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -\] -By computing the derivatives of $\chi^2$ with respect to $\beta_0$ and $\beta_1$ show that these are given by -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -\] -and -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -For a linear fit (a first-order polynomial) we don't need to invert a matrix!! -Defining -\[ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -\] - -\[ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -\] - -\[ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -\] - -\[ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -\] - -\[ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -\] - -we obtain - -\[ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -\] - -\[ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -\] - -This approach (different linear and non-linear regression) suffers -often from both being underdetermined and overdetermined in the -unknown coefficients $\beta_i$. A better approach is to use the -Singular Value Decomposition (SVD) method discussed below. Or using -Lasso and Ridge regression. See below. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Fitting an Equation of State for Dense Nuclear Matter} - -Before we continue, let us introduce yet another example. We are going to fit the -nuclear equation of state using results from many-body calculations. -The equation of state we have made available here, as function of -density, has been derived using modern nucleon-nucleon potentials with -\href{{https://www.sciencedirect.com/science/article/pii/S0370157399001106}}{the addition of three-body -forces}. This -time the file is presented as a standard \textbf{csv} file. - -The beginning of the Python code here is similar to what you have seen before, -with the same initializations and declarations. We use also \textbf{pandas} -again, rather extensively in order to organize our data. - -The difference now is that we use \textbf{Scikit-Learn's} regression tools -instead of our own matrix inversion implementation. Furthermore, we -sneak in \textbf{Ridge} regression (to be discussed below) which includes a -hyperparameter $\lambda$, also to be explained below. - -% !split -\subsection*{The code} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import matplotlib.pyplot as plt -import sklearn.linear_model as skl -from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error - -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organize the data into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops -X = np.zeros((len(Density),4)) -X[:,3] = Density**(4.0/3.0) -X[:,2] = Density -X[:,1] = Density**(2.0/3.0) -X[:,0] = 1 - -# We use now Scikit-Learn's linear regressor and ridge regressor -# OLS part -clf = skl.LinearRegression().fit(X, Energies) -ytilde = clf.predict(X) -EoS['Eols'] = ytilde -# The mean squared error -print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(Energies, ytilde)) -# Mean absolute error -print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde)) -print(clf.coef_, clf.intercept_) - -# The Ridge regression with a hyperparameter lambda = 0.1 -_lambda = 0.1 -clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies) -yridge = clf_ridge.predict(X) -EoS['Eridge'] = yridge -# The mean squared error -print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(Energies, yridge)) -# Mean absolute error -print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge)) -print(clf_ridge.coef_, clf_ridge.intercept_) - -fig, ax = plt.subplots() -ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$') -ax.set_ylabel(r'Energy per particle') -ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2, - label='Theoretical data') -ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m', - label='OLS') -ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g', - label='Ridge $\lambda = 0.1$') -ax.legend() -save_fig("EoSfitting") -plt.show() -\end{minted} - -The above simple polynomial in density $\rho$ gives an excellent fit -to the data. Can you give an interpretation of the various powers of $\rho$? - -We note also that there is a small deviation between the -standard OLS and the Ridge regression at higher densities. We discuss this in more detail -below. - - -% !split -\subsection*{Splitting our Data in Training and Test data} - -It is normal in essentially all Machine Learning studies to split the -data in a training set and a test set (sometimes also an additional -validation set). \textbf{Scikit-Learn} has an own function for this. There -is no explicit recipe for how much data should be included as training -data and say test data. An accepted rule of thumb is to use -approximately $2/3$ to $4/5$ of the data as training data. We will -postpone a discussion of this splitting to the end of these notes and -our discussion of the so-called \textbf{bias-variance} tradeoff. Here we -limit ourselves to repeat the above equation of state fitting example -but now splitting the data into a training set and a test set. - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organized into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops -X = np.zeros((len(Density),5)) -X[:,0] = 1 -X[:,1] = Density**(2.0/3.0) -X[:,2] = Density -X[:,3] = Density**(4.0/3.0) -X[:,4] = Density**(5.0/3.0) -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) -# matrix inversion to find beta -beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train) -# and then make the prediction -ytilde = X_train @ beta -print("Training R2") -print(R2(y_train,ytilde)) -print("Training MSE") -print(MSE(y_train,ytilde)) -ypredict = X_test @ beta -print("Test R2") -print(R2(y_test,ypredict)) -print("Test MSE") -print(MSE(y_test,ypredict)) -\end{minted} - - -% !split -\subsection*{The singular value decomposition} - - -% --- begin paragraph admon --- -\paragraph{} - -The examples we have looked at so far are cases where we normally can -invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion as we -did both for the masses and the fitting of the equation of state, -leads to row vectors of the design matrix which are essentially -orthogonal due to the polynomial character of our model. This may -however not the be case in general and a standard matrix inversion -algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit -the coupling constant of the widely used Ising model. -There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. - -This is given by the \textbf{Singular Value Decomposition} algorithm, perhaps -the most powerful linear algebra algorithm. Let us look at a -different example where we may have problems with the standard matrix -inversion algorithm. Thereafter we dive into the math of the SVD. -% --- end paragraph admon --- - - - -% !split -\subsection*{The Ising model} - -The one-dimensional Ising model with nearest neighbor interaction, no -external field and a constant coupling constant $J$ is given by - -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\end{align} - -where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins -in the system is determined by $L$. For the one-dimensional system -there is no phase transition. - -We will look at a system of $L = 40$ spins with a coupling constant of -$J = 1$. To get enough training data we will generate 10000 states -with their respective energies. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import make_axes_locatable -import seaborn as sns -import scipy.linalg as scl -from sklearn.model_selection import train_test_split -import tqdm -sns.set(color_codes=True) -cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') - -L = 40 -n = int(1e4) - -spins = np.random.choice([-1, 1], size=(n, L)) -J = 1.0 - -energies = np.zeros(n) - -for i in range(n): - energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) -\end{minted} - -Here we use ordinary least squares -regression to predict the energy for the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use linear regression to fit a value for -the coupling constant to achieve this. - -% !split -\subsection*{Reformulating the problem to suit regression} - -A more general form for the one-dimensional Ising model is - -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\end{align} - -Here we allow for interactions beyond the nearest neighbors and a state dependent -coupling constant. This latter expression can be formulated as -a matrix-product -\begin{align} - \bm{H} = \bm{X} J, -\end{align} - -where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the -elements $-J_{jk}$. This form of writing the energy fits perfectly -with the form utilized in linear regression, that is - -\begin{align} - \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}, -\end{align} - -We split the data in training and test data as discussed in the previous example - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X = np.zeros((n, L ** 2)) -for i in range(n): - X[i] = np.outer(spins[i], spins[i]).ravel() -y = energies -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) -\end{minted} - -% !split -\subsection*{Linear regression} - -In the ordinary least squares method we choose the cost function - -\begin{align} - C(\bm{X}, \bm{\beta})= \frac{1}{n}\left\{(\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y})\right\}. -\end{align} - -We then find the extremal point of $C$ by taking the derivative with respect to $\bm{\beta}$ as discussed above. -This yields the expression for $\bm{\beta}$ to be - -\[ - \bm{\beta} = \frac{\bm{X}^T \bm{y}}{\bm{X}^T \bm{X}}, -\] - -which immediately imposes some requirements on $\bm{X}$ as there must exist -an inverse of $\bm{X}^T \bm{X}$. If the expression we are modeling contains an -intercept, i.e., a constant term, we must make sure that the -first column of $\bm{X}$ consists of $1$. We do this here - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X_train_own = np.concatenate( - (np.ones(len(X_train))[:, np.newaxis], X_train), - axis=1 -) -X_test_own = np.concatenate( - (np.ones(len(X_test))[:, np.newaxis], X_test), - axis=1 -) -\end{minted} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray: - return scl.inv(x.T @ x) @ (x.T @ y) -beta = ols_inv(X_train_own, y_train) -\end{minted} - - -% !split -\subsection*{Singular Value decomposition} - -Doing the inversion directly turns out to be a bad idea since the matrix -$\bm{X}^T\bm{X}$ is singular. An alternative approach is to use the \textbf{singular -value decomposition}. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for $\bm{\beta}$ as - -\[ - \bm{\beta} = \bm{X}^{+}\bm{y}, -\] - -where the pseudoinverse of $\bm{X}$ is given by - -\[ - \bm{X}^{+} = \frac{\bm{X}^T}{\bm{X}^T\bm{X}}. -\] - -Using singular value decomposition we can decompose the matrix $\bm{X} = \bm{U}\bm{\Sigma} \bm{V}^T$, -where $\bm{U}$ and $\bm{V}$ are orthogonal(unitary) matrices and $\bm{\Sigma}$ contains the singular values (more details below). -where $X^{+} = V\Sigma^{+} U^T$. This reduces the equation for -$\omega$ to -\begin{align} - \bm{\beta} = \bm{V}\bm{\Sigma}^{+} \bm{U}^T \bm{y}. -\end{align} - -Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as $\mathcal{O}(n^3)$, where $n$ is the number of elements in a -general matrix. Instead, doing $QR$-factorization and solving the -linear system as an equation would reduce this down to -$\mathcal{O}(n^2)$ operations. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray: - u, s, v = scl.svd(x) - return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y -\end{minted} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -beta = ols_svd(X_train_own,y_train) -\end{minted} - -When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -J = beta[1:].reshape(L, L) -\end{minted} - -A way of looking at the coefficients in $J$ is to plot the matrices as images. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J, **cmap_args) -plt.title("OLS", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) -plt.show() -\end{minted} -It is interesting to note that OLS -considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as -valid matrix elements for $J$. -In our discussion below on hyperparameters and Ridge and Lasso regression we will see that -this problem can be removed, partly and only with Lasso regression. - -In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? - - -% !split -\subsection*{Linear Regression Problems} - -One of the typical problems we encounter with linear regression, in particular -when the matrix $\bm{X}$ (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of $\bm{X}$ -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} - -The columns of $\bm{X}$ are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of $\mathbf{X}$ is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. - -Super-collinearity of an $(n \times p)$-dimensional design matrix $\mathbf{X}$ implies -that the inverse of the matrix $\bm{X}^T\bm{x}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -\begin{align*} -\bm{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -We see easily that $\mbox{det}(\bm{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined. -This is equivalent to saying that the matrix $\bm{X}$ has at least an eigenvalue which is zero. - - -% !split -\subsection*{Fixing the singularity} - -If our design matrix $\bm{X}$ which enters the linear regression problem -\begin{align} -\bm{\beta} & = (\bm{X}^{T} \bm{X})^{-1} \bm{X}^{T} \bm{y}, -\end{align} -has linearly dependent column vectors, we will not be able to compute the inverse -of $\bm{X}^T\bm{X}$ and we cannot find the parameters (estimators) $\beta_i$. -The estimators are only well-defined if $(\bm{X}^{T}\bm{X})^{-1}$ exits. -This is more likely to happen when the matrix $\bm{X}$ is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters $\beta_i$ cannot be estimated. - -A cheap \emph{ad hoc} approach is simply to add a small diagonal component to the matrix to invert, that is we change -\[ -\bm{X}^{T} \bm{X} \rightarrow \bm{X}^{T} \bm{X}+\lambda \bm{I}, -\] -where $\bm{I}$ is the identity matrix. When we discuss \textbf{Ridge} regression this is actually what we end up evaluating. The parameter $\lambda$ is called a hyperparameter. More about this later. - - - -% !split -\subsection*{Basic math of the SVD} - - -From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is -a so-called \href{{https://en.wikipedia.org/wiki/Normal_matrix}}{normal matrix}, that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$ -we have $\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ or if $\bm{X}\in {\mathbb{C}}^{n\times n}$ we have $\bm{X}\bm{X}^{\dagger}=\bm{X}^{\dagger}\bm{X}$. -The matrix has then a set of eigenpairs - -\[ -(\lambda_1,\bm{u}_1),\dots, (\lambda_n,\bm{u}_n), -and the eigenvalues are given by the diagonal matrix -\[ -\bm{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). -\] -The matrix $\bm{X}$ can be written in terms of an orthogonal/unitary transformation $\bm{U}$ -\[ -\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T, -\] -with $\bm{U}\bm{U}^T=\bm{I}$ or $\bm{U}\bm{U}^{\dagger}=\bm{I}$. - -Not all square matrices are diagonalizable. A matrix like the one discussed above -\[ -\bm{X} = \begin{bmatrix} -1& -1 \\ -1& -1\\ -\end{bmatrix} -\] -is not diagonalizable, it is a so-called \href{{https://en.wikipedia.org/wiki/Defective_matrix}}{defective matrix}. It is easy to see that the condition -$\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ is not fulfilled. - - -% !split -\subsection*{The SVD, a Fantastic Algorithm} - - -However, and this is the strength of the SVD algorithm, any general -matrix $\bm{X}$ can be decomposed in terms of a diagonal matrix and -two orthogonal/unitary matrices. The \href{{https://en.wikipedia.org/wiki/Singular_value_decomposition}}{Singular Value Decompostion -(SVD) theorem} -states that a general $m\times n$ matrix $\bm{X}$ can be written in -terms of a diagonal matrix $\bm{\Sigma}$ of dimensionality $n\times n$ -and two orthognal matrices $\bm{U}$ and $\bm{V}$, where the first has -dimensionality $m \times m$ and the last dimensionality $n\times n$. -We have then - -\[ -\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T -\] - -As an example, the above defective matrix can be decomposed as - -\[ -\bm{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T, -\] - -with eigenvalues $\sigma_1=2$ and $\sigma_2=0$. -The SVD exits always! - - -% !split -\subsection*{Another Example} - -Consider the following matrix which can be SVD decomposed as - -\[ -\bm{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T. -\] - -This is a $3\times 2$ matrix which is decomposed in terms of a -$3\times 3$ matrix $\bm{U}$, and a $2\times 2$ matrix $\bm{V}$. It is easy to see -that $\bm{U}$ and $\bm{V}$ are orthogonal (how?). - -And the SVD -decomposition (singular values) gives eigenvalues -$\sigma_i\geq\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=2$, the -eigenvalues (singular values) are zero. - -In the general case, where our design matrix $\bm{X}$ has dimension -$n\times p$, the matrix is thus decomposed into an $n\times n$ -orthogonal matrix $\bm{U}$, a $p\times p$ orthogonal matrix $\bm{V}$ -and a diagonal matrix $\bm{\Sigma}$ with $r=\mathrm{min}(n,p)$ -singular values $\sigma_i\lg 0$ on the main diagonal and zeros filling -the rest of the matrix. There are at most $p$ singular values -assuming that $n > p$. In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have $p > n$. These are often cases that lead to -near singular or singular matrices. - -The columns of $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors. - -% !split -\subsection*{Economy-size SVD} - -If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n -\times n$. The last $n-p$ columns of $\bm{U}$ become however -irrelevant in our calculations since they are multiplied with the -zeros in $\bm{\Sigma}$. - -The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, $\bm{\Sigma}$, along with the columns -in either $\bm{U}$ or $\bm{V}$ that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. - -If $n > p$, we keep only the first $p$ columns of $\bm{U}$ and $\bm{\Sigma}$ has dimension $p\times p$. -If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\Sigma}$ has dimension $n\times n$. -The $n=p$ case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. - -% !split -\subsection*{Mathematical Properties} - -There are several interesting mathematical properties which will be -relevant when we are going to discuss the differences between say -ordinary least squares (OLS) and \textbf{Ridge} regression. - -We have from OLS that the parameters of the linear approximation are given by -\[ -\bm{\tilde{y}} = \bm{X}\bm{\beta} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] - -The matrix to invert can be rewritten in terms of our SVD decomposition as - -\[ -\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T. -\] -Using the orthogonality properties of $\bm{U}$ we have - -\[ -\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T = \bm{V}\bm{D}\bm{V}^T, -\] -with $\bm{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. - -This means that -\[ -(\bm{X}^T\bm{X})\bm{V} = \bm{V}\bm{D}, -\] -that is the eigenvectors of $(\bm{X}^T\bm{X})$ are given by the columns of the right singular matrix of $\bm{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that -\[ -(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}, -\] -that is, the eigenvectors of $(\bm{X}\bm{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. - -Going back to our OLS equation we have -\[ -\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}. -\] -We will come back to this expression when we discuss Ridge regression. - - -% !split -\subsection*{Ridge and LASSO Regression} - -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_{\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\}. -\] -or we can state it as -\[ -{\displaystyle \min_{\bm{\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 \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, -\] -where we have used the definition of a norm-2 vector, that is -\[ -\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. -\] - -By minimizing the above equation with respect to the parameters -$\bm{\beta}$ we could then obtain an analytical expression for the -parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by -defining a new cost function to be optimized, that is - -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 -\] - -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. By defining - -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, -\] - -we have a new optimization equation -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\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 \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. -\] - - -% !split -\subsection*{More on Ridge Regression} - -Using the matrix-vector expression for Ridge regression, - -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, -\] - -by taking the derivatives with respect to $\bm{\beta}$ we obtain then -a slightly modified matrix inversion problem which for finite values -of $\lambda$ does not suffer from singularity problems. We obtain - -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, -\] - -with $\bm{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. - -We see that Ridge regression is nothing but the standard -OLS with a modified diagonal term added to $\bm{X}^T\bm{X}$. The -consequences, in particular for our discussion of the bias-variance -are rather interesting. - -Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had -\[ -(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}. -\] - -We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as -\[ -\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y} -\] - - -For Ridge regression this becomes - -\[ -\bm{X}\bm{\beta}^{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, -\] - -with the vectors $\bm{u}_j$ being the columns of $\bm{U}$. - -% !split -\subsection*{Interpreting the Ridge results} - -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 $\bm{y}$ with respect to the -orthonormal basis $\bm{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}$. - -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. -Actually, calculating the variance of $\bm{X}\bm{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$. -With a parameter $\lambda$ we can thus shrink the role of specific parameters. - - -% !split -\subsection*{More interpretations} - -For the sake of simplicity, let us assume that the design matrix is orthonormal, that is - -\[ -\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. -\] - -In this case the standard OLS results in -\[ -\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, -\] - -and - -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\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. - -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, \href{{https://arxiv.org/abs/1509.09169}}{Wessel van Wieringen's} article is highly recommended. -Similarly, \href{{https://arxiv.org/abs/1803.08823}}{Mehta et al's article} is also recommended. - -% !split -\subsection*{Where are we going?} - -Before we proceed, we need to rethink what we have been doing. In our -eager to fit the data, we have omitted several important elements in -our regression analysis. In what follows we will -\begin{enumerate} -\item look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff - -\item introduce resampling techniques like cross-validation, bootstrapping and jackknife and more -\end{enumerate} - -\noindent -This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. - - - - - -% !split -\subsection*{Resampling methods} - -% --- begin paragraph admon --- -\paragraph{} -Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. -% --- end paragraph admon --- - - - -% !split -\subsection*{Resampling approaches can be computationally expensive} - -% --- begin paragraph admon --- -\paragraph{} - -Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. -% --- end paragraph admon --- - - - -% !split -\subsection*{Why resampling methods ?} - -% --- begin paragraph admon --- -\paragraph{Statistical analysis.} - -\begin{itemize} -\item Our simulations can be treated as \emph{computer experiments}. This is particularly the case for Monte Carlo methods - -\item The results can be analysed with the same statistical tools as we would use analysing experimental data. - -\item As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. -\end{itemize} - -\noindent -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistical analysis} - -% --- begin paragraph admon --- -\paragraph{} - -\begin{itemize} -\item As in other experiments, many numerical experiments have two classes of errors: -\begin{itemize} - - \item Statistical errors - - \item Systematical errors - -\end{itemize} - -\noindent -\item Statistical errors can be estimated using standard tools from statistics - -\item Systematical errors are method specific and must be treated differently from case to case. -\end{itemize} - -\noindent -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -The \emph{probability distribution function (PDF)} is a function -$p(x)$ on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of $X$ occur: -\[ -p(x) = \mathrm{prob}(X=x) -\] -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us -the \emph{density} of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval $[a,\,b]$ is then just the integral: -\[ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx -\] -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Statistics, moments} - -% --- begin paragraph admon --- -\paragraph{} -A particularly useful class of special expectation values are the -\emph{moments}. The $n$-th moment of the PDF $p$ is defined as -follows: -\[ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx -\] -The zero-th moment $\langle 1\rangle$ is just the normalization condition of -$p$. The first moment, $\langle x\rangle$, is called the \emph{mean} of $p$ -and often denoted by the letter $\mu$: -\[ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, central moments} - -% --- begin paragraph admon --- -\paragraph{} -A special version of the moments is the set of \emph{central moments}, -the n-th central moment defined as: -\[ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -\] -The zero-th and first central moments are both trivial, equal $1$ and -$0$, respectively. But the second central moment, known as the -\emph{variance} of $p$, is of particular interest. For the stochastic -variable $X$, the variance is denoted as $\sigma^2_X$ or $\mathrm{var}(X)$: -\begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\end{align} -The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle}$ is called the \emph{standard deviation} of $p$. It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the \emph{spread} of $p$ around its mean. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, covariance} - -% --- begin paragraph admon --- -\paragraph{} -Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set $\{X_i\}$ of $n$ -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF $P(x_1,\dots,x_n)$. The \emph{covariance} of two -of the stochastic variables, $X_i$ and $X_j$, is defined as follows: -\begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\label{eq:def_covariance} -\end{align} -with -\[ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, more covariance} - -% --- begin paragraph admon --- -\paragraph{} -If we consider the above covariance as a matrix $C_{ij}=\mathrm{cov}(X_i,\,X_j)$, then the diagonal elements are just the familiar -variances, $C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i)$. It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables $X_i$ and -$X_j$, ($i\neq j$): -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle \\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\end{align} -% --- end paragraph admon --- - - - - - -% !split -\subsection*{Statistics, independent variables} - -% --- begin paragraph admon --- -\paragraph{} -If $X_i$ and $X_j$ are independent, we get -$\langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle$, resulting in $\mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j)$. - -Also useful for us is the covariance of linear combinations of -stochastic variables. Let $\{X_i\}$ and $\{Y_i\}$ be two sets of -stochastic variables. Let also $\{a_i\}$ and $\{b_i\}$ be two sets of -scalars. Consider the linear combination: -\[ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j -\] -By the linearity of the expectation value -\[ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, more variance} - -% --- begin paragraph admon --- -\paragraph{} -Now, since the variance is just $\mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i)$, we get -the variance of the linear combination $U = \sum_i a_i X_i$: -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\label{eq:variance_linear_combination} -\end{equation} -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -\[ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -\] -\[ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -\] -which will become very useful in our study of the error in the mean -value of a set of measurements. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics and stochastic processes} - -% --- begin paragraph admon --- -\paragraph{} -A \emph{stochastic process} is a process that produces sequentially a -chain of values: -\[ -\{x_1, x_2,\dots\,x_k,\dots\}. -\] -We will call these -values our \emph{measurements} and the entire set as our measured -\emph{sample}. The action of measuring all the elements of a sample -we will call a stochastic \emph{experiment} since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF $p_X^{\phantom X}(x)$, where $X$ is just the formal symbol for the -stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of -trying to determine the full distribution $p$ we are often only -interested in finding the few lowest moments, like the mean -$\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Statistics and sample variables} - -% --- begin paragraph admon --- -\paragraph{} -In practical situations a sample is always of finite size. Let that -size be $n$. The expectation value of a sample, the \emph{sample mean}, is then defined as follows: -\[ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -\] -The \emph{sample variance} is: -\[ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -\] -its square root being the \emph{standard deviation of the sample}. The -\emph{sample covariance} is: -\[ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, sample variance and covariance} - -% --- begin paragraph admon --- -\paragraph{} -Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq.~(\ref{eq:def_covariance}) is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. - -These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean $\mu_X$, variance $\mathrm{var}(X)$ -and covariance $\mathrm{cov}(X,Y)$. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, law of large numbers} - -% --- begin paragraph admon --- -\paragraph{} -The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean $\mu_X^{\phantom X}$ of the chosen PDF: -\[ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} -\] -The sample mean $\bar{x}_n$ works therefore as an estimate of the true -mean $\mu_X^{\phantom X}$. - -What we need to find out is how good an approximation $\bar{x}_n$ is to -$\mu_X^{\phantom X}$. In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the \emph{error} of the sample mean, or -just sample error, and denote it by $\mathrm{err}_X^{\phantom X}$. In -practice, we will only be able to produce an \emph{estimate} of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Statistics, more on sample error} - -% --- begin paragraph admon --- -\paragraph{} -Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements $x_i$ -can be associated with its own stochastic variable $X_i$. The -stochastic variable $\overline X_n$ for the sample mean $\bar{x}_n$ is -then just a linear combination, already familiar to us: -\[ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i -\] -All the coefficients are just equal $1/n$. The PDF of $\overline X_n$, -denoted by $p_{\overline X_n}(x)$ is the desired PDF of the sample -means. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -The probability density of obtaining a sample mean $\bar x_n$ -is the product of probabilities of obtaining arbitrary values $x_1, -x_2,\dots,x_n$ with the constraint that the mean of the set $\{x_i\}$ -is $\bar x_n$: -\[ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 -\] -And in particular we are interested in its variance $\mathrm{var}(\overline X_n)$. -% --- end paragraph admon --- - - - - - -% !split -\subsection*{Statistics, central limit theorem} - -% --- begin paragraph admon --- -\paragraph{} -It is generally not possible to express $p_{\overline X_n}(x)$ in a -closed form given an arbitrary PDF $p_X^{\phantom X}$ and a number -$n$. But for the limit $n\to\infty$ it is possible to make an -approximation. The very important result is called \emph{the central limit theorem}. It tells us that as $n$ goes to infinity, -$p_{\overline X_n}(x)$ approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, $\mu_{X}^{\phantom X}$ -and $\sigma_{X}^{2}$, respectively: -\begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\label{eq:central_limit_gaussian} -\end{equation} -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, more technicalities} - -% --- begin paragraph admon --- -\paragraph{} -The desired variance -$\mathrm{var}(\overline X_n)$, i.e.~the sample error squared -$\mathrm{err}_X^2$, is given by: -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\label{eq:error_exact} -\end{equation} -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -$\mu_{X_i}^{\phantom X}$ of the stochastic variables $X_i$. To -calculate these requires that we know the true multivariate PDF of all -the $X_i$. But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the $X_i$, estimating all properties of -$X_i$ through the measurements of the sample. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -Our estimate of $\mu_{X_i}^{\phantom X}$ is then the sample mean $\bar x$ -itself, in accordance with the the central limit theorem: -\[ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x -\] -Using $\bar x$ in place of $\mu_{X_i}^{\phantom X}$ we can give an -\emph{estimate} of the covariance in Eq.~(\ref{eq:error_exact}) -\[ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, -\] -resulting in -\[ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics and sample variance} - -% --- begin paragraph admon --- -\paragraph{} -By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables $X_i$ -\[ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, -\] -which is approximated as -\begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\label{eq:var_estimate_i_think} -\end{equation} - -Now we can calculate an estimate of the error -$\mathrm{err}_X^{\phantom X}$ of the sample mean $\bar x_n$: -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\label{eq:error_estimate} -\end{align} -which is nothing but the sample covariance divided by the number of -measurements in the sample. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, uncorrelated results} - -% --- begin paragraph admon --- -\paragraph{} - -In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables $X_i$ are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: -\[ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), -\] -resulting in -\begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\label{eq:error_estimate_uncorrel} -\end{equation} -where in the second step we have used Eq.~(\ref{eq:var_estimate_i_think}). -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, computations} - -% --- begin paragraph admon --- -\paragraph{} -For computational purposes one usually splits up the estimate of -$\mathrm{err}_X^2$, given by Eq.~(\ref{eq:error_estimate}), into two -parts -\[ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), -\] -which equals -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k 0$. We say then that the ridge estimator is biased. - -We can also compute the variance as - -\[ -\mbox{Var}[\bm{\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 $\bm{\beta}$ goes to zero. - -With this, we can compute the difference - -\[ -\mbox{Var}[\bm{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\bm{\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 $\bm{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. - -% !split -\subsection*{Cross-validation} - -Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e.~the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. - -The setting of \textbf{original} and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the -\emph{training set}, plays the role of \textbf{original} data on which the model is -built. The second of these data sets, called the \emph{test set}, plays the -role of the \textbf{novel} data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of $\lambda$ using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. - - -% !split -\subsection*{Computationally expensive} - -The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: - -\begin{itemize} -\item The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set. - -\item In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set. -\end{itemize} - -\noindent -% !split -\subsection*{Various steps in cross-validation} - -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this $k$-fold cross-validation structures the data splitting. The -samples are divided into $k$ more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the $k$ subsets -involves a degree of randomness. This may be fully excluded when -choosing $k=n$. This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -% !split -\subsection*{How to set up the cross-validation for Ridge and/or Lasso} - -\begin{itemize} -\item Define a range of interest for the penalty parameter. - -\item Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. - -\item Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, as -\end{itemize} - -\noindent -\begin{align*} -\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T} -\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1} -\bm{X}_{-i, \ast}^{T} \bm{y}_{-i} -\end{align*} - -\begin{itemize} -\item Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. - -\item Repeat the first three steps such that each sample plays the role of the test set once. - -\item Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the \emph{cross-validated log-likelihood}. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as -\end{itemize} - -\noindent -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} - -\begin{itemize} -\item The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions. -\end{itemize} - -\noindent -% !split -\subsection*{Resampling methods: Jackknife and Bootstrap} - -Two famous -resampling methods are the \textbf{independent bootstrap} and \textbf{the jackknife}. - -The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as \textbf{the dependent bootstrap}. - -The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of $\overline{X}$ (which often is the case), then there is no -need for bootstrapping. - -% !split -\subsection*{Resampling methods: Jackknife} - -The Jackknife works by making many replicas of the estimator $\widehat{\theta}$. -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\bm{x} = (x_1,x_2,\cdots,X_n)$. -Let $\bm{x}_i$ denote the vector -\[ -\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -\] - -which equals the vector $\bm{x}$ with the exception that observation -number $i$ is left out. Using this notation, define -$\widehat{\theta}_i$ to be the estimator -$\widehat{\theta}$ computed using $\vec{X}_i$. - - -% !split -\subsection*{Jackknife code example} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from numpy import * -from numpy.random import randint, randn -from time import time - -def jackknife(data, stat): - n = len(data);t = zeros(n); inds = arange(n); t0 = time() - ## 'jackknifing' by leaving out an observation for each i - for i in range(n): - t[i] = stat(delete(data,i) ) - - # analysis - print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :") - print("original bias std. error") - print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5)) - - return t - - -# Returns mean of data samples -def stat(data): - return mean(data) - - -mu, sigma = 100, 15 -datapoints = 10000 -x = mu + sigma*random.randn(datapoints) -# jackknife returns the data sample -t = jackknife(x, stat) - -\end{minted} - - -% !split -\subsection*{Resampling methods: Bootstrap} - -% --- begin paragraph admon --- -\paragraph{} -Bootstrapping is a nonparametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: -\begin{enumerate} -\item The bootstrap is quite general, although there are some cases in which it fails. - -\item Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. - -\item It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. - -\item It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples). -\end{enumerate} - -\noindent -% --- end paragraph admon --- - - - - -% !split -\subsection*{Resampling methods: Bootstrap background} - -Since $\widehat{\theta} = \widehat{\theta}(\bm{X})$ is a function of random variables, -$\widehat{\theta}$ itself must be a random variable. Thus it has -a pdf, call this function $p(\bm{t})$. The aim of the bootstrap is to -estimate $p(\bm{t})$ by the relative frequency of -$\widehat{\theta}$. You can think of this as using a histogram -in the place of $p(\bm{t})$. If the relative frequency closely -resembles $p(\vec{t})$, then using numerics, it is straight forward to -estimate all the interesting parameters of $p(\bm{t})$ using point -estimators. - - -% !split -\subsection*{Resampling methods: More Bootstrap background} - -In the case that $\widehat{\theta}$ has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of $X_i$, $p(x)$, had been known, then it would have -been straight forward to do this by: -\begin{enumerate} -\item Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \cdots, X_n^*)$. - -\item Then using these numbers, we could compute a replica of $\widehat{\theta}$ called $\widehat{\theta}^*$. -\end{enumerate} - -\noindent -By repeated use of (1) and (2), many -estimates of $\widehat{\theta}$ could have been obtained. The -idea is to use the relative frequency of $\widehat{\theta}^*$ -(think of a histogram) as an estimate of $p(\bm{t})$. - -% !split -\subsection*{Resampling methods: Bootstrap approach} - -But -unless there is enough information available about the process that -generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general -unknown. Therefore, \href{{https://projecteuclid.org/euclid.aos/1176344552}}{Efron in 1979} asked the -question: What if we replace $p(x)$ by the relative frequency -of the observation $X_i$; if we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - - -Instead of generating the histogram for the relative -frequency of the observation $X_i$, just draw the values -$(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector -$\bm{X}$. - -% !split -\subsection*{Resampling methods: Bootstrap steps} - -The independent bootstrap works like this: - -\begin{enumerate} -\item Draw with replacement $n$ numbers for the observed variables $\bm{x} = (x_1,x_2,\cdots,x_n)$. - -\item Define a vector $\bm{x}^*$ containing the values which were drawn from $\bm{x}$. - -\item Using the vector $\bm{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\bm{x}^*$. - -\item Repeat this process $k$ times. -\end{enumerate} - -\noindent -When you are done, you can draw a histogram of the relative frequency -of $\widehat \theta^*$. This is your estimate of the probability -distribution $p(t)$. Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of $\widehat{\theta}^*$. Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of $\widehat -\theta$, apply the etsimator $\widehat \sigma^2$ to the values -$\widehat \theta ^*$. - - -% !split -\subsection*{Code example for the Bootstrap method} - -The following code starts with a Gaussian distribution with mean value -$\mu =100$ and variance $\sigma=15$. We use this to generate the data -used in the bootstrap analysis. The bootstrap analysis returns a data -set after a given number of bootstrap operations (as many as we have -data points). This data set consists of estimated mean values for each -bootstrap operation. The histogram generated by the bootstrap method -shows that the distribution for these mean values is also a Gaussian, -centered around the mean value $\mu=100$ but with standard deviation -$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in -this case the same as the number of original data points). The value -of the standard deviation is what we expect from the central limit -theorem. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from numpy import * -from numpy.random import randint, randn -from time import time -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt - -# Returns mean of bootstrap samples -def stat(data): - return mean(data) - -# Bootstrap algorithm -def bootstrap(data, statistic, R): - t = zeros(R); n = len(data); inds = arange(n); t0 = time() - # non-parametric bootstrap - for i in range(R): - t[i] = statistic(data[randint(0,n,n)]) - - # analysis - print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") - print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) - return t - - -mu, sigma = 100, 15 -datapoints = 10000 -x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample -t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data -n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) - -# add a 'best fit' line -y = mlab.normpdf( binsboot, mean(t), std(t)) -lt = plt.plot(binsboot, y, 'r--', linewidth=1) -plt.xlabel('Smarts') -plt.ylabel('Probability') -plt.axis([99.5, 100.6, 0, 3.0]) -plt.grid(True) - -plt.show() - -\end{minted} - - -% !split -\subsection*{Code Example for Cross-validation and $k$-fold Cross-validation} - -The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import matplotlib.pyplot as plt -from sklearn.model_selection import KFold -from sklearn.linear_model import Ridge -from sklearn.model_selection import cross_val_score -from sklearn.preprocessing import PolynomialFeatures - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(3155) - -# Generate the data. -nsamples = 100 -x = np.random.randn(nsamples) -y = 3*x**2 + np.random.randn(nsamples) - -## Cross-validation on Ridge regression using KFold only - -# Decide degree on polynomial to fit -poly = PolynomialFeatures(degree = 6) - -# Decide which values of lambda to use -nlambdas = 500 -lambdas = np.logspace(-3, 5, nlambdas) - -# Initialize a KFold instance -k = 5 -kfold = KFold(n_splits = k) - -# Perform the cross-validation to estimate MSE -scores_KFold = np.zeros((nlambdas, k)) - -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - j = 0 - for train_inds, test_inds in kfold.split(x): - xtrain = x[train_inds] - ytrain = y[train_inds] - - xtest = x[test_inds] - ytest = y[test_inds] - - Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) - ridge.fit(Xtrain, ytrain[:, np.newaxis]) - - Xtest = poly.fit_transform(xtest[:, np.newaxis]) - ypred = ridge.predict(Xtest) - - scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) - - j += 1 - i += 1 - - -estimated_mse_KFold = np.mean(scores_KFold, axis = 1) - -## Cross-validation using cross_val_score from sklearn along with KFold - -# kfold is an instance initialized above as: -# kfold = KFold(n_splits = k) - -estimated_mse_sklearn = np.zeros(nlambdas) -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - - X = poly.fit_transform(x[:, np.newaxis]) - estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) - - # cross_val_score return an array containing the estimated negative mse for every fold. - # we have to the the mean of every array in order to get an estimate of the mse of the model - estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) - - i += 1 - -## Plot and compare the slightly different ways to perform cross-validation - -plt.figure() - -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') - -plt.xlabel('log10(lambda)') -plt.ylabel('mse') - -plt.legend() - -plt.show() - -\end{minted} - - -% !split -\subsection*{The bias-variance tradeoff} - - -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset $\mathcal{L}$ consisting of the data -$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$. - -Let us assume that the true data is generated from a noisy model - -\[ -\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon} -\] - -where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$. - -In our derivation of the ordinary least squares method we defined then -an approximation to the function $f$ in terms of the parameters -$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model, -that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$. - -Thereafter we found the parameters $\bm{\beta}$ by optimizing the means squared error via the so-called cost function -\[ -C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]. -\] - -We can rewrite this as -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\sigma^2. -\] - -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error $\bm{\epsilon}$. - -To derive this equation, we need to recall that the variance of $\bm{y}$ and $\bm{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\bm{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\bm{\tilde{y}}$. -We use a more compact notation in terms of the expectation value -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}})^2\right], -\] -and adding and subtracting $\mathbb{E}\left[\bm{\tilde{y}}\right]$ we get -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}}+\mathbb{E}\left[\bm{\tilde{y}}\right]-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right], -\] -which, using the abovementioned expectation values can be rewritten as -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\bm{\tilde{y}}\right]+\sigma^2, -\] -that is the rewriting in terms of the so-called bias, the variance of the model $\bm{\tilde{y}}$ and the variance of $\bm{\epsilon}$. - - - - - -% !split -\subsection*{Example code for Bias-Variance tradeoff} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 500 -n_boostraps = 100 -degree = 18 # A quite high value, just to show. -noise = 0.1 - -# Make data set. -x = np.linspace(-1, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) - -# Hold out some test data that is never used in training. -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -# Combine x transformation and model into one operation. -# Not neccesary, but convenient. -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - -# The following (m x n_bootstraps) matrix holds the column vectors y_pred -# for each bootstrap iteration. -y_pred = np.empty((y_test.shape[0], n_boostraps)) -for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - - # Evaluate the new model on the same test data each time. - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - -# Note: Expectations and variances taken w.r.t. different training -# data sets, hence the axis=1. Subsequent means are taken across the test data -# set in order to obtain a total value, but before this we have error/bias/variance -# calculated per data point in the test set. -# Note 2: The use of keepdims=True is important in the calculation of bias as this -# maintains the column vector form. Dropping this yields very unexpected results. -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) -print('Error:', error) -print('Bias^2:', bias) -print('Var:', variance) -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) - -plt.plot(x[::5, :], y[::5, :], label='f(x)') -plt.scatter(x_test, y_test, label='Data points') -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') -plt.legend() -plt.show() - -\end{minted} - - -% !split -\subsection*{Understanding what happens} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 40 -n_boostraps = 100 -maxdegree = 14 - - -# Make data set. -x = np.linspace(-3, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) -error = np.zeros(maxdegree) -bias = np.zeros(maxdegree) -variance = np.zeros(maxdegree) -polydegree = np.zeros(maxdegree) -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -for degree in range(maxdegree): - model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - y_pred = np.empty((y_test.shape[0], n_boostraps)) - for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) - variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) - print('Polynomial degree:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) - -plt.plot(polydegree, np.log10(error), label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') -plt.legend() -plt.show() - - - - -\end{minted} - -% !split -\subsection*{Summing up} - - - - -The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - - - -The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below $Var(\epsilon)$, the irreducible error. - - -What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - - -% !split -\subsection*{Another Example rom Scikit-Learn's Repository} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -""" -============================ -Underfitting vs. Overfitting -============================ - -This example demonstrates the problems of underfitting and overfitting and -how we can use linear regression with polynomial features to approximate -nonlinear functions. The plot shows the function that we want to approximate, -which is a part of the cosine function. In addition, the samples from the -real function and the approximations of different models are displayed. The -models have polynomial features of different degrees. We can see that a -linear function (polynomial with degree 1) is not sufficient to fit the -training samples. This is called **underfitting**. A polynomial of degree 4 -approximates the true function almost perfectly. However, for higher degrees -the model will **overfit** the training data, i.e. it learns the noise of the -training data. -We evaluate quantitatively **overfitting** / **underfitting** by using -cross-validation. We calculate the mean squared error (MSE) on the validation -set, the higher, the less likely the model generalizes correctly from the -training data. -""" - -print(__doc__) - -import numpy as np -import matplotlib.pyplot as plt -from sklearn.pipeline import Pipeline -from sklearn.preprocessing import PolynomialFeatures -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import cross_val_score - - -def true_fun(X): - return np.cos(1.5 * np.pi * X) - -np.random.seed(0) - -n_samples = 30 -degrees = [1, 4, 15] - -X = np.sort(np.random.rand(n_samples)) -y = true_fun(X) + np.random.randn(n_samples) * 0.1 - -plt.figure(figsize=(14, 5)) -for i in range(len(degrees)): - ax = plt.subplot(1, len(degrees), i + 1) - plt.setp(ax, xticks=(), yticks=()) - - polynomial_features = PolynomialFeatures(degree=degrees[i], - include_bias=False) - linear_regression = LinearRegression() - pipeline = Pipeline([("polynomial_features", polynomial_features), - ("linear_regression", linear_regression)]) - pipeline.fit(X[:, np.newaxis], y) - - # Evaluate the models using crossvalidation - scores = cross_val_score(pipeline, X[:, np.newaxis], y, - scoring="neg_mean_squared_error", cv=10) - - X_test = np.linspace(0, 1, 100) - plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") - plt.plot(X_test, true_fun(X_test), label="True function") - plt.scatter(X, y, edgecolor='b', s=20, label="Samples") - plt.xlabel("x") - plt.ylabel("y") - plt.xlim((0, 1)) - plt.ylim((-2, 2)) - plt.legend(loc="best") - plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( - degrees[i], -scores.mean(), scores.std())) -plt.show() -\end{minted} - - - -% !split -\subsection*{The one-dimensional Ising model} - -Let us bring back the Ising model again, but now with an additional -focus on Ridge and Lasso regression as well. We repeat some of the -basic parts of the Ising model and the setup of the training and test -data. The one-dimensional Ising model with nearest neighbor -interaction, no external field and a constant coupling constant $J$ is -given by - -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\end{align} -where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins in the system is determined by $L$. For the one-dimensional system there is no phase transition. - -We will look at a system of $L = 40$ spins with a coupling constant of $J = 1$. To get enough training data we will generate 10000 states with their respective energies. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import make_axes_locatable -import seaborn as sns -import scipy.linalg as scl -from sklearn.model_selection import train_test_split -import sklearn.linear_model as skl -import tqdm -sns.set(color_codes=True) -cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') - -L = 40 -n = int(1e4) - -spins = np.random.choice([-1, 1], size=(n, L)) -J = 1.0 - -energies = np.zeros(n) - -for i in range(n): - energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) -\end{minted} - -A more general form for the one-dimensional Ising model is - -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\end{align} - -Here we allow for interactions beyond the nearest neighbors and a more -adaptive coupling matrix. This latter expression can be formulated as -a matrix-product on the form -\begin{align} - H = X J, -\end{align} - -where $X_{jk} = s_j s_k$ and $J$ is the matrix consisting of the -elements $-J_{jk}$. This form of writing the energy fits perfectly -with the form utilized in linear regression, viz. -\begin{align} - \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}. -\end{align} -We organize the data as we did above -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X = np.zeros((n, L ** 2)) -for i in range(n): - X[i] = np.outer(spins[i], spins[i]).ravel() -y = energies -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96) - -X_train_own = np.concatenate( - (np.ones(len(X_train))[:, np.newaxis], X_train), - axis=1 -) - -X_test_own = np.concatenate( - (np.ones(len(X_test))[:, np.newaxis], X_test), - axis=1 -) -\end{minted} - -We will do all fitting with \textbf{Scikit-Learn}, - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -clf = skl.LinearRegression().fit(X_train, y_train) -\end{minted} -When extracting the $J$-matrix we make sure to remove the intercept -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -J_sk = clf.coef_.reshape(L, L) -\end{minted} -And then we plot the results -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_sk, **cmap_args) -plt.title("LinearRegression from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) -plt.show() -\end{minted} -The results perfectly with our previous discussion where we used our own code. - -% !split -\subsection*{Ridge regression} - -Having explored the ordinary least squares we move on to ridge -regression. In ridge regression we include a \textbf{regularizer}. This -involves a new cost function which leads to a new estimate for the -weights $\bm{\beta}$. This results in a penalized regression problem. The -cost function is given by - -\begin{align} - C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \bm{\beta}^T\bm{\beta}. -\end{align} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -_lambda = 0.1 -clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train) -J_ridge_sk = clf_ridge.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_ridge_sk, **cmap_args) -plt.title("Ridge from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - -plt.show() -\end{minted} - -% !split -\subsection*{LASSO regression} - -In the \textbf{Least Absolute Shrinkage and Selection Operator} (LASSO)-method we get a third cost function. - -\begin{align} - C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \sqrt{\bm{\beta}^T\bm{\beta}}. -\end{align} - -Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from \textbf{Scikit-Learn}. - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train) -J_lasso_sk = clf_lasso.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_lasso_sk, **cmap_args) -plt.title("Lasso from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - -plt.show() -\end{minted} - -It is quite striking how LASSO breaks the symmetry of the coupling -constant as opposed to ridge and OLS. We get a sparse solution with -$J_{j, j + 1} = -1$. - - - -% !split -\subsection*{Performance as function of the regularization parameter} - -We see how the different models perform for a different set of values for $\lambda$. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -lambdas = np.logspace(-4, 5, 10) - -train_errors = { - "ols_sk": np.zeros(lambdas.size), - "ridge_sk": np.zeros(lambdas.size), - "lasso_sk": np.zeros(lambdas.size) -} - -test_errors = { - "ols_sk": np.zeros(lambdas.size), - "ridge_sk": np.zeros(lambdas.size), - "lasso_sk": np.zeros(lambdas.size) -} - -plot_counter = 1 - -fig = plt.figure(figsize=(32, 54)) - -for i, _lambda in enumerate(tqdm.tqdm(lambdas)): - for key, method in zip( - ["ols_sk", "ridge_sk", "lasso_sk"], - [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)] - ): - method = method.fit(X_train, y_train) - - train_errors[key][i] = method.score(X_train, y_train) - test_errors[key][i] = method.score(X_test, y_test) - - omega = method.coef_.reshape(L, L) - - plt.subplot(10, 5, plot_counter) - plt.imshow(omega, **cmap_args) - plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda)) - plot_counter += 1 - -plt.show() -\end{minted} - -We see that LASSO reaches a good solution for low -values of $\lambda$, but will "wither" when we increase $\lambda$ too -much. Ridge is more stable over a larger range of values for -$\lambda$, but eventually also fades away. - -% !split -\subsection*{Finding the optimal value of $\lambda$} - -To determine which value of $\lambda$ is best we plot the accuracy of -the models when predicting the training and the testing set. We expect -the accuracy of the training set to be quite good, but if the accuracy -of the testing set is much lower this tells us that we might be -subject to an overfit model. The ideal scenario is an accuracy on the -testing set that is close to the accuracy of the training set. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fig = plt.figure(figsize=(20, 14)) - -colors = { - "ols_sk": "r", - "ridge_sk": "y", - "lasso_sk": "c" -} - -for key in train_errors: - plt.semilogx( - lambdas, - train_errors[key], - colors[key], - label="Train {0}".format(key), - linewidth=4.0 - ) - -for key in test_errors: - plt.semilogx( - lambdas, - test_errors[key], - colors[key] + "--", - label="Test {0}".format(key), - linewidth=4.0 - ) -plt.legend(loc="best", fontsize=18) -plt.xlabel(r"$\lambda$", fontsize=18) -plt.ylabel(r"$R^2$", fontsize=18) -plt.tick_params(labelsize=18) -plt.show() -\end{minted} - -From the above figure we can see that LASSO with $\lambda = 10^{-2}$ -achieves a very good accuracy on the test set. This by far surpasses the -other models for all values of $\lambda$. - - - -% !split -\subsection*{Further Exercises} - -\paragraph{Exercise 1.} -We will 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). -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -x = np.random.rand(100,1) -y = 5*x*x+0.1*np.random.randn(100,1) -\end{minted} - -\begin{enumerate} -\item Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial. - -\item Use thereafter \textbf{scikit-learn} (see again the examples in the regression slides) and compare with your own code. - -\item Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as -\end{enumerate} - -\noindent -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] - -You can use the functionality included in scikit-learn. If you feel -for it, you can use your own program and define functions which -compute the above two functions. Discuss the meaning of these -results. Try also to vary the coefficient in front of the added -stochastic noise term and discuss the quality of the fits. - - - - -\paragraph{Exercise 2, variance of the parameters $\beta$ in linear regression.} -Show that the variance of the parameters $\beta$ in the linear regression method (chapter 3, equation (3.8) of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}) is given as - -\[ -\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, -\] -with -\[ -\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, -\] -where we have assumed that we fit a function of degree $p-1$ (for example a polynomial in $x$). - - - -\paragraph{Exercise 3.} -This exercise is a continuation of exercise 1. 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. You can use the code under the Regression as an example on how to use the Ridge and the Lasso 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). -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -x = np.random.rand(100,1) -y = 5*x*x+0.1*np.random.randn(100,1) -\end{minted} - -\begin{enumerate} -\item Write your own code for the Ridge method and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 1. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. - -\item Repeat the above but using the functionality of \textbf{scikit-learn}. Compare your code with the results from \textbf{scikit-learn}. Remember to run with the same random numbers for generating $x$ and $y$. - -\item Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parametrizing 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 that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$) or use the functionality of \textbf{scikit-learn} and compute their variances. Discuss the results of these variances as functions - -\item Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results. - -\item Try to implement the cross-validation as well. - -\item Finally, using \textbf{scikit-learn} or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as -\end{enumerate} - -\noindent -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] -Discuss these quantities as functions of the variable $\lambda$ in the Ridge and Lasso regression methods. - -\paragraph{Exercise 4.} -We will study how -to fit polynomials to a specific two-dimensional function called -\href{{http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf}}{Franke's -function}. This -is a function which has been widely used when testing various interpolation and fitting -algorithms. Furthermore, after having established the model and the -method, we will employ resamling techniques such as the cross-validation and/or -the bootstrap methods, in order to perform a proper assessment of our models. - - -The Franke function, which is a weighted sum of four exponentials reads as follows -\begin{align*} -f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ -&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. -\end{align*} - -The function will be defined for $x,y\in [0,1]$. Our first step will -be to perform an OLS regression analysis of this function, trying out -a polynomial fit with an $x$ and $y$ dependence of the form $[x, y, -x^2, y^2, xy, \dots]$. We will also include cross-validation and -bootstrap as resampling techniques. As in homeworks 1 and 2, we -can use a uniform distribution to set up the arrays of values for $x$ -and $y$, or as in the example below just a fix values for $x$ and $y$ with a given step size. -In this case we will have two predictors and need to fit a -function (for example a polynomial) of $x$ and $y$. Thereafter we will -repeat much of the same procedure using the the Ridge and -Lasso regression methods, introducing thus a dependence on the bias -(penalty) $\lambda$. - - -The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from mpl_toolkits.mplot3d import Axes3D -import matplotlib.pyplot as plt -from matplotlib import cm -from matplotlib.ticker import LinearLocator, FormatStrFormatter -import numpy as np -from random import random, seed - -fig = plt.figure() -ax = fig.gca(projection='3d') - -# Make data. -x = np.arange(0, 1, 0.05) -y = np.arange(0, 1, 0.05) -x, y = np.meshgrid(x,y) - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -z = FrankeFunction(x, y) - -# Plot the surface. -surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm, - linewidth=0, antialiased=False) - -# Customize the z axis. -ax.set_zlim(-0.10, 1.40) -ax.zaxis.set_major_locator(LinearLocator(10)) -ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) - -# Add a color bar which maps values to colors. -fig.colorbar(surf, shrink=0.5, aspect=5) - -plt.show() - -\end{minted} - - -We will thus again generate our own dataset for a function $\mathrm{FrankeFunction}(x,y)$ where -$x,y \in [0,1]$ could be defined by random numbers computed with the uniform -distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition -an added stochastic noise to this function using the normal distribution $\cal{N}(0,1)$. - -Write your own code (using either a matrix inversion or a singular value decomposition from e.g., \textbf{numpy} ) or use your code from exercises 1 and 3 -and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\beta$ by computing their variances, evaluate the Mean Squared error (MSE) -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] - -Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm -and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models. - - -Write then your own code for the Ridge method, either using matrix -inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the -previous exercise (for the same polynomials and include resampling -techniques) but now for different values of $\lambda$. Compare and -analyze your results with those obtained with standard OLS. Study the -dependence on $\lambda$ while also varying eventually the strength of -the noise in your expression for $\mathrm{FrankeFunction}(x,y)$. - -Then perform the same studies but now with Lasso regression. Use the functionalities of -\textbf{scikit-learn}. Give a critical discussion of the three methods and a -judgement of which model fits the data best. - - -% ------------------- end of main content --------------- - -\end{document} - diff --git a/doc/src/Regression/Regression-reveal.html b/doc/src/Regression/Regression-reveal.html deleted file mode 100644 index e55e0387b..000000000 --- a/doc/src/Regression/Regression-reveal.html +++ /dev/null @@ -1,4558 +0,0 @@ - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - - - - - - - - - - -
- - - - -

Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis

- -

- - -

-Morten Hjorth-Jensen [1, 2] -
- -

 
- - -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

 
-

Jul 22, 2019

-
-

- -

- © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
-
- - -
-

Why Linear Regression (aka Ordinary Least Squares and family)

- -

-Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \). - -

    -

  • Method of choice for fitting a continuous function!
  • -

  • Gives an excellent introduction to central Machine Learning features with understandable pedagogical links to other methods like Neural Networks, Support Vector Machines etc
  • -

  • Analytical expression for the fitting parameters \( \boldsymbol{\beta} \)
  • -

  • Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more
  • -

  • Analytical relation with probabilistic interpretations
  • -

  • Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics
  • -

  • Easy to code! And links well with classification problems and logistic regression and neural networks
  • -

  • Allows for easy hands-on understanding of gradient descent methods
  • -

  • and many more features
  • -
-

- -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. -

- - -
-

Regression analysis, overarching aims

-
- -

-Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. - -

-A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with - -

    -

  • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
  • -

  • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
  • -

  • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
  • -
-

- - The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. -

-
- - -
-

Regression analysis, overarching aims II

-
- -

-Consider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix -\( \mathbf{X} \). - -

-The matrix \( \mathbf{X} \) is called the design -matrix. Additional information of the samples is available in the -form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is -generally referred to as the response variable. The aim of -regression analysis is to explain \( \boldsymbol{y} \) in terms of -\( \boldsymbol{X} \) through a functional relationship like \( y_i = -f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of -\( f(\cdot) \) is available, it is common to assume a linear relationship -between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to -the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T} \) are the regression parameters. - -

-Linear regression gives us a set of analytical equations for the parameters \( \beta_j \). - - -

-
- - -
-

Examples

-
- -

-In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), -consider the model we discussed for describing nuclear binding energies. - -

-There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. -Assuming -

 
-$$ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, -$$ -

 
- -we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. -This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a -\( p\times n \) matrix \( \boldsymbol{X} \). - -

-Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \) - - -

-
- - -
-

General linear models

-
- -

-Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. - -

-Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is -

 
-$$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, -$$ -

 
- -where \( \epsilon_i \) is the error in our approximation. - - -

-
- - -
-

Rewriting the fitting procedure as a linear algebra problem

-
- -

-For every set of values \( y_i,x_i \) we have thus the corresponding set of equations -

 
-$$ -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ -

 
-

-
- - -
-

Rewriting the fitting procedure as a linear algebra problem, more details

-
- -

-Defining the vectors -

 
-$$ -\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -$$ -

 
- -and -

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

 
- -and -

 
-$$ -\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -$$ -

 
- -and the design matrix -

 
-$$ -\boldsymbol{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -$$ -

 
- -we can rewrite our equations as -

 
-$$ -\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. -$$ -

 
- -The above design matrix is called a Vandermonde matrix. -

-
- - -
-

Generalizing the fitting procedure as a linear algebra problem

-
- -

-We are obviously not limited to the above polynomial expansions. We -could replace the various powers of \( x \) with elements of Fourier -series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j -x_i)} \), or time series or other orthogonal functions. For every set -of values \( y_i,x_i \) we can then generalize the equations to - -

 
-$$ -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ -

 
- -

-Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case! -

-
- - -
-

Generalizing the fitting procedure as a linear algebra problem

-
- -

-We redefine in turn the matrix \( \boldsymbol{X} \) as -

 
-$$ -\boldsymbol{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -$$ -

 
- -and without loss of generality we rewrite again our equations as -

 
-$$ -\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. -$$ -

 
- -The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? -

-
- - -
-

Optimizing our parameters

-
- -

-We have defined the matrix \( \boldsymbol{X} \) via the equations -

 
-$$ -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ -

 
- -

-As we noted above, we stayed with a system with the design matrix - \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define -our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. - - -

-
- - -
-

Our model for the nuclear binding energies

- -

-In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. - -

-We restate the parts of the code we are most interested in. -

- - -

# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("MassEval2016.dat"),'r')
-
-
-# Read the experimental data with Pandas
-Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
-              names=('N', 'Z', 'A', 'Element', 'Ebinding'),
-              widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
-              header=39,
-              index_col=False)
-
-# Extrapolated values are indicated by '#' in place of the decimal place, so
-# the Ebinding column won't be numeric. Coerce to float and drop these entries.
-Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
-Masses = Masses.dropna()
-# Convert from keV to MeV.
-Masses['Ebinding'] /= 1000
-
-# Group the DataFrame by nucleon number, A.
-Masses = Masses.groupby('A')
-# Find the rows of the grouped DataFrame with the maximum binding energy.
-Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
-A = Masses['A']
-Z = Masses['Z']
-N = Masses['N']
-Element = Masses['Element']
-Energies = Masses['Ebinding']
-
-# Now we set up the design matrix X
-X = np.zeros((len(A),5))
-X[:,0] = 1
-X[:,1] = A
-X[:,2] = A**(2.0/3.0)
-X[:,3] = A**(-1.0/3.0)
-X[:,4] = A**(-1.0)
-# Then nice printout using pandas
-DesignMatrix = pd.DataFrame(X)
-DesignMatrix.index = A
-DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
-display(DesignMatrix)
-
-

-With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as -

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

 
- -throughout these lectures. -

- - -
-

Optimizing our parameters, more details

-
- -

-With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as -

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

 
- -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely -

 
-$$ -C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, -$$ -

 
- -or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as -

 
-$$ -C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}. -$$ -

 
- -This function is one possible way to define the so-called cost function. - -

-It is also common to define -the function \( Q \) as - -

 
-$$ -C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, -$$ -

 
- -since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out. -

-
- - -
-

Interpretations and optimizing our parameters

-
- -

-The function -

 
-$$ -C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, -$$ -

 
- -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) -

 
-$$ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -$$ -

 
- -

-where \( \langle y_i \rangle \) is the mean value. Keep in mind also that -till now we have treated \( y_i \) as the exact value. Normally, the -response (dependent or outcome) variable \( y_i \) the outcome of a -numerical experiment or another type of experiment and is thus only an -approximation to the true value. It is then always accompanied by an -error estimate, often limited to a statistical error estimate given by -the standard deviation discussed earlier. In the discussion here we -will treat \( y_i \) as our exact value for the response variable. - -

-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem -

 
-$$ -{\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\}. -$$ -

 
- -In practical terms it means we will require -

 
-$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -$$ -

 
- -which results in -

 
-$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -$$ -

 
- -or in a matrix-vector form as -

 
-$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). -$$ -

 
- - -

-
- - -
-

Interpretations and optimizing our parameters

-
- -

-We can rewrite -

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

 
- -as -

 
-$$ -\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, -$$ -

 
- -and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution -

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

 
- -

-We note also that since our design matrix is defined as \( \boldsymbol{X}\in -{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in -{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), -in our case \( p=5 \) meaning that we end up with inverting a small -\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional -matrices to invert. The methods discussed here and for many other -supervised learning algorithms like classification with logistic -regression or support vector machines, exhibit dimensionalities which -allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \). - - -

-
- - -
-

Interpretations and optimizing our parameters

-
- -

-The residuals \( \boldsymbol{\epsilon} \) are in turn given by -

 
-$$ -\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, -$$ -

 
- -and with -

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

 
- -we have -

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

 
- -meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. - - -

- -

-Let us now return to our nuclear binding energies and simply code the above equations. -

- - -
-

Own code for Ordinary Least Squares

- -

-It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to -write -

- - -

# matrix inversion to find beta
-beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
-# and then make the prediction
-ytilde = X @ beta
-
-

-Alternatively, you can use the least squares functionality in Numpy as -

- - -

fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
-ytildenp = np.dot(fit,X.T)
-
-

-And finally we plot our fit with and compare with data -

- - -

Masses['Eapprox']  = ytilde
-# Generate a plot comparing the experimental with the fitted values values.
-fig, ax = plt.subplots()
-ax.set_xlabel(r'$A = N + Z$')
-ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
-ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
-            label='Ame2016')
-ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
-            label='Fit')
-ax.legend()
-save_fig("Masses2016OLS")
-plt.show()
-
-
- - -
-

Adding error analysis and training set up

- -

-We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. -Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as -

- - -

def R2(y_data, y_model):
-    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
-
-

-and we would be using it as -

- - -

print(R2(Energies,ytilde))
-
-

-We can easily add our MSE score as -

- - -

def MSE(y_data,y_model):
-    n = np.size(y_model)
-    return np.sum((y_data-y_model)**2)/n
-
-print(MSE(Energies,ytilde))
-
-

-and finally the relative error as -

- - -

def RelativeError(y_data,y_model):
-    return abs((y_data-y_model)/y_data)
-print(RelativeError(Energies, ytilde))
-
-
- - -
-

The \( \chi^2 \) function

-
- -

-Normally, the response (dependent or outcome) variable \( y_i \) is the -outcome of a numerical experiment or another type of experiment and is -thus only an approximation to the true value. It is then always -accompanied by an error estimate, often limited to a statistical error -estimate given by the standard deviation discussed earlier. In the -discussion here we will treat \( y_i \) as our exact value for the -response variable. - -

-Introducing the standard deviation \( \sigma_i \) for each measurement -\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) -as - -

 
-$$ -\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, -$$ -

 
- -where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - - -

-
- - -
-

The \( \chi^2 \) function

-
- -

-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring -

 
-$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -$$ -

 
- -which results in -

 
-$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -$$ -

 
- -or in a matrix-vector form as -

 
-$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). -$$ -

 
- -where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \). -

-
- - -
-

The \( \chi^2 \) function

-
- -

-We can rewrite -

 
-$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), -$$ -

 
- -as -

 
-$$ -\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, -$$ -

 
- -and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution -

 
-$$ -\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. -$$ -

 
-

-
- - -
-

The \( \chi^2 \) function

-
- -

-If we then introduce the matrix -

 
-$$ -\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, -$$ -

 
- -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) -

 
-$$ -\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} -$$ -

 
- -We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise) -

 
-$$ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -$$ -

 
- -resulting in -

 
-$$ -\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! -$$ -

 
-

-
- - -
-

The \( \chi^2 \) function

-
- -

-The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write -

 
-$$ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -$$ -

 
- -By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by -

 
-$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -$$ -

 
- -and -

 
-$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -$$ -

 
-

-
- - -
-

The \( \chi^2 \) function

-
- -

-For a linear fit (a first-order polynomial) we don't need to invert a matrix!! -Defining -

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

 
- -

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

 
- -

 
-$$ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -$$ -

 
- -

 
-$$ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -$$ -

 
- -

 
-$$ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -$$ -

 
- -

-we obtain - -

 
-$$ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -$$ -

 
- -

 
-$$ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -$$ -

 
- -

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

-
- - -
-

Fitting an Equation of State for Dense Nuclear Matter

- -

-Before we continue, let us introduce yet another example. We are going to fit the -nuclear equation of state using results from many-body calculations. -The equation of state we have made available here, as function of -density, has been derived using modern nucleon-nucleon potentials with -the addition of three-body -forces. This -time the file is presented as a standard csv file. - -

-The beginning of the Python code here is similar to what you have seen before, -with the same initializations and declarations. We use also pandas -again, rather extensively in order to organize our data. - -

-The difference now is that we use Scikit-Learn's regression tools -instead of our own matrix inversion implementation. Furthermore, we -sneak in Ridge regression (to be discussed below) which includes a -hyperparameter \( \lambda \), also to be explained below. -

- - -
-

The code

- -

- - -

# Common imports
-import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-import matplotlib.pyplot as plt
-import sklearn.linear_model as skl
-from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as  csv file and organize the data into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-#  The design matrix now as function of various polytrops
-X = np.zeros((len(Density),4))
-X[:,3] = Density**(4.0/3.0)
-X[:,2] = Density
-X[:,1] = Density**(2.0/3.0)
-X[:,0] = 1
-
-# We use now Scikit-Learn's linear regressor and ridge regressor
-# OLS part
-clf = skl.LinearRegression().fit(X, Energies)
-ytilde = clf.predict(X)
-EoS['Eols']  = ytilde
-# The mean squared error                               
-print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
-# Explained variance score: 1 is perfect prediction                                 
-print('Variance score: %.2f' % r2_score(Energies, ytilde))
-# Mean absolute error                                                           
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
-print(clf.coef_, clf.intercept_)
-
-# The Ridge regression with a hyperparameter lambda = 0.1
-_lambda = 0.1
-clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
-yridge = clf_ridge.predict(X)
-EoS['Eridge']  = yridge
-# The mean squared error                               
-print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
-# Explained variance score: 1 is perfect prediction                                 
-print('Variance score: %.2f' % r2_score(Energies, yridge))
-# Mean absolute error                                                           
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
-print(clf_ridge.coef_, clf_ridge.intercept_)
-
-fig, ax = plt.subplots()
-ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
-ax.set_ylabel(r'Energy per particle')
-ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,
-            label='Theoretical data')
-ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
-            label='OLS')
-ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
-            label='Ridge $\lambda = 0.1$')
-ax.legend()
-save_fig("EoSfitting")
-plt.show()
-
-

-The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. Can you give an interpretation of the various powers of \( \rho \)? - -

-We note also that there is a small deviation between the -standard OLS and the Ridge regression at higher densities. We discuss this in more detail -below. -

- - -
-

Splitting our Data in Training and Test data

- -

-It is normal in essentially all Machine Learning studies to split the -data in a training set and a test set (sometimes also an additional -validation set). Scikit-Learn has an own function for this. There -is no explicit recipe for how much data should be included as training -data and say test data. An accepted rule of thumb is to use -approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will -postpone a discussion of this splitting to the end of these notes and -our discussion of the so-called bias-variance tradeoff. Here we -limit ourselves to repeat the above equation of state fitting example -but now splitting the data into a training set and a test set. - -

- - -

import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from sklearn.model_selection import train_test_split
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-def R2(y_data, y_model):
-    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
-def MSE(y_data,y_model):
-    n = np.size(y_model)
-    return np.sum((y_data-y_model)**2)/n
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as  csv file and organized into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-#  The design matrix now as function of various polytrops
-X = np.zeros((len(Density),5))
-X[:,0] = 1
-X[:,1] = Density**(2.0/3.0)
-X[:,2] = Density
-X[:,3] = Density**(4.0/3.0)
-X[:,4] = Density**(5.0/3.0)
-# We split the data in test and training data
-X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
-# matrix inversion to find beta
-beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
-# and then make the prediction
-ytilde = X_train @ beta
-print("Training R2")
-print(R2(y_train,ytilde))
-print("Training MSE")
-print(MSE(y_train,ytilde))
-ypredict = X_test @ beta
-print("Test R2")
-print(R2(y_test,ypredict))
-print("Test MSE")
-print(MSE(y_test,ypredict))
-
-
- - -
-

The singular value decomposition

- -

-

- -

-The examples we have looked at so far are cases where we normally can -invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we -did both for the masses and the fitting of the equation of state, -leads to row vectors of the design matrix which are essentially -orthogonal due to the polynomial character of our model. This may -however not the be case in general and a standard matrix inversion -algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit -the coupling constant of the widely used Ising model. -There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. - -

-This is given by the Singular Value Decomposition algorithm, perhaps -the most powerful linear algebra algorithm. Let us look at a -different example where we may have problems with the standard matrix -inversion algorithm. Thereafter we dive into the math of the SVD. - - -

-
- - -
-

The Ising model

- -

-The one-dimensional Ising model with nearest neighbor interaction, no -external field and a constant coupling constant \( J \) is given by - -

 
-$$ -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\tag{1} -\end{align} -$$ -

 
- -

-where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins -in the system is determined by \( L \). For the one-dimensional system -there is no phase transition. - -

-We will look at a system of \( L = 40 \) spins with a coupling constant of -\( J = 1 \). To get enough training data we will generate 10000 states -with their respective energies. - -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from mpl_toolkits.axes_grid1 import make_axes_locatable
-import seaborn as sns
-import scipy.linalg as scl
-from sklearn.model_selection import train_test_split
-import tqdm
-sns.set(color_codes=True)
-cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
-
-L = 40
-n = int(1e4)
-
-spins = np.random.choice([-1, 1], size=(n, L))
-J = 1.0
-
-energies = np.zeros(n)
-
-for i in range(n):
-    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-
-

-Here we use ordinary least squares -regression to predict the energy for the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use linear regression to fit a value for -the coupling constant to achieve this. -

- - -
-

Reformulating the problem to suit regression

- -

-A more general form for the one-dimensional Ising model is - -

 
-$$ -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\tag{2} -\end{align} -$$ -

 
- -

-Here we allow for interactions beyond the nearest neighbors and a state dependent -coupling constant. This latter expression can be formulated as -a matrix-product -

 
-$$ -\begin{align} - \boldsymbol{H} = \boldsymbol{X} J, -\tag{3} -\end{align} -$$ -

 
- -

-where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the -elements \( -J_{jk} \). This form of writing the energy fits perfectly -with the form utilized in linear regression, that is - -

 
-$$ -\begin{align} - \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}, -\tag{4} -\end{align} -$$ -

 
- -

-We split the data in training and test data as discussed in the previous example - -

- - -

X = np.zeros((n, L ** 2))
-for i in range(n):
-    X[i] = np.outer(spins[i], spins[i]).ravel()
-y = energies
-X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
-
-
- - -
-

Linear regression

- -

-In the ordinary least squares method we choose the cost function - -

 
-$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}. -\tag{5} -\end{align} -$$ -

 
- -

-We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above. -This yields the expression for \( \boldsymbol{\beta} \) to be - -

 
-$$ - \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}}, -$$ -

 
- -

-which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist -an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an -intercept, i.e., a constant term, we must make sure that the -first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here - -

- - -

X_train_own = np.concatenate(
-    (np.ones(len(X_train))[:, np.newaxis], X_train),
-    axis=1
-)
-X_test_own = np.concatenate(
-    (np.ones(len(X_test))[:, np.newaxis], X_test),
-    axis=1
-)
-
-

- - -

def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
-    return scl.inv(x.T @ x) @ (x.T @ y)
-beta = ols_inv(X_train_own, y_train)
-
-
- - -
-

Singular Value decomposition

- -

-Doing the inversion directly turns out to be a bad idea since the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular -value decomposition. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as - -

 
-$$ - \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y}, -$$ -

 
- -

-where the pseudoinverse of \( \boldsymbol{X} \) is given by - -

 
-$$ - \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}. -$$ -

 
- -

-Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \), -where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below). -where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for -\( \omega \) to -

 
-$$ -\begin{align} - \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}. -\tag{6} -\end{align} -$$ -

 
- -

-Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a -general matrix. Instead, doing \( QR \)-factorization and solving the -linear system as an equation would reduce this down to -\( \mathcal{O}(n^2) \) operations. - -

- - -

def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
-    u, s, v = scl.svd(x)
-    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
-
-

- - -

beta = ols_svd(X_train_own,y_train)
-
-

-When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here - -

- - -

J = beta[1:].reshape(L, L)
-
-

-A way of looking at the coefficients in \( J \) is to plot the matrices as images. - -

- - -

fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J, **cmap_args)
-plt.title("OLS", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-plt.show()
-
-

-It is interesting to note that OLS -considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as -valid matrix elements for \( J \). -In our discussion below on hyperparameters and Ridge and Lasso regression we will see that -this problem can be removed, partly and only with Lasso regression. - -

-In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? -

- - -
-

Linear Regression Problems

- -

-One of the typical problems we encounter with linear regression, in particular -when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \) -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix -

 
-$$ -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} -$$ -

 
- -

-The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. - -

-Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{x} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -

 
-$$ -\begin{align*} -\boldsymbol{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -$$ -

 
- -We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. -This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero. -

- - -
-

Fixing the singularity

- -

-If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem -

 
-$$ -\begin{align} -\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, -\tag{7} -\end{align} -$$ -

 
- -has linearly dependent column vectors, we will not be able to compute the inverse -of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \). -The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits. -This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters \( \beta_i \) cannot be estimated. - -

-A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change -

 
-$$ -\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, -$$ -

 
- -where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later. -

- - -
-

Basic math of the SVD

- -

-From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is -a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \) -we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \). -The matrix has then a set of eigenpairs - -

 
-$$ -(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), -$$ -

 
- -and the eigenvalues are given by the diagonal matrix -

 
-$$ -\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). -$$ -

 
- -The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) -

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

 
- -with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \). - -

-Not all square matrices are diagonalizable. A matrix like the one discussed above -

 
-$$ -\boldsymbol{X} = \begin{bmatrix} -1& -1 \\ -1& -1\\ -\end{bmatrix} -$$ -

 
- -is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition -\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled. -

- - -
-

The SVD, a Fantastic Algorithm

- -

-However, and this is the strength of the SVD algorithm, any general -matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and -two orthogonal/unitary matrices. The Singular Value Decompostion -(SVD) theorem -states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in -terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( n\times n \) -and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has -dimensionality \( m \times m \) and the last dimensionality \( n\times n \). -We have then - -

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

 
- -

-As an example, the above defective matrix can be decomposed as - -

 
-$$ -\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ -

 
- -

-with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). -The SVD exits always! -

- - -
-

Another Example

- -

-Consider the following matrix which can be SVD decomposed as - -

 
-$$ -\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. -$$ -

 
- -

-This is a \( 3\times 2 \) matrix which is decomposed in terms of a -\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see -that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?). - -

-And the SVD -decomposition (singular values) gives eigenvalues -\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), the -eigenvalues (singular values) are zero. - -

-In the general case, where our design matrix \( \boldsymbol{X} \) has dimension -\( n\times p \), the matrix is thus decomposed into an \( n\times n \) -orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) -and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) -singular values \( \sigma_i\lg 0 \) on the main diagonal and zeros filling -the rest of the matrix. There are at most \( p \) singular values -assuming that \( n > p \). In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have \( p > n \). These are often cases that lead to -near singular or singular matrices. - -

-The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors. -

- - -
-

Economy-size SVD

- -

-If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n -\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however -irrelevant in our calculations since they are multiplied with the -zeros in \( \boldsymbol{\Sigma} \). - -

-The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns -in either \( \boldsymbol{U} \) or \( \boldsymbol{V} \) that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. - -

-If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). -If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). -The \( n=p \) case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. -

- - -
-

Mathematical Properties

- -

-There are several interesting mathematical properties which will be -relevant when we are going to discuss the differences between say -ordinary least squares (OLS) and Ridge regression. - -

-We have from OLS that the parameters of the linear approximation are given by -

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

 
- -

-The matrix to invert can be rewritten in terms of our SVD decomposition as - -

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

 
- -Using the orthogonality properties of \( \boldsymbol{U} \) we have - -

 
-$$ -\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T, -$$ -

 
- -with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared. - -

-This means that -

 
-$$ -(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D}, -$$ -

 
- -that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that -

 
-$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}, -$$ -

 
- -that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same. - -

-Going back to our OLS equation we have -

 
-$$ -\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. -$$ -

 
- -We will come back to this expression when we discuss Ridge regression. -

- - -
-

Ridge and LASSO Regression

- -

-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}\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 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}. -$$ -

 
- -

-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 - -

 
-$$ -{\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. -$$ -

 
-

- - -
-

More on Ridge Regression

- -

-Using the matrix-vector expression for Ridge regression, - -

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

 
- -

-by 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 - -

 
-$$ -\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. - -

-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 -are rather interesting. - -

-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had -

 
-$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}. -$$ -

 
- -

-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as -

 
-$$ -\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} -$$ -

 
- -

-For Ridge regression this becomes - -

 
-$$ -\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\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} \). -

- - -
-

Interpreting the Ridge results

- -

-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} \). - -

-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. -Actually, calculating the variance of \( \boldsymbol{X}\boldsymbol{v}_j \) shows that this quantity is equal to \( \sigma_j^2/n \). -With a parameter \( \lambda \) we can thus shrink the role of specific parameters. -

- - -
-

More interpretations

- -

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

 
-$$ -\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. -$$ -

 
- -

-In this case the standard OLS results in -

 
-$$ -\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^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. - -

-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. -

- - -
-

Where are we going?

- -

-Before we proceed, we need to rethink what we have been doing. In our -eager to fit the data, we have omitted several important elements in -our regression analysis. In what follows we will - -

    -

  1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
  2. -

  3. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
  4. -
-

- -This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. -

- - -
-

Resampling methods

-
- -

-Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. -

-
- - -
-

Resampling approaches can be computationally expensive

-
- -

-Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. - - -

-
- - -
-

Why resampling methods ?

-
-Statistical analysis. -
    -

  • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
  • -

  • The results can be analysed with the same statistical tools as we would use analysing experimental data.
  • -

  • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
  • -
-
-
- - -
-

Statistical analysis

-
- -
    -

  • As in other experiments, many numerical experiments have two classes of errors:
  • - -
      - -

    • Statistical errors
    • - -

    • Systematical errors
    • -
    -

  • Statistical errors can be estimated using standard tools from statistics
  • -

  • Systematical errors are method specific and must be treated differently from case to case.
  • -
-
-
- - -
-

Statistics

-
- -

-The probability distribution function (PDF) is a function -\( p(x) \) on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of \( X \) occur: -

 
-$$ -p(x) = \mathrm{prob}(X=x) -$$ -

 
- -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around \( x \) to be \( p(x)dx \). The continuous function \( p(x) \) then gives us -the density of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval \( [a,\,b] \) is then just the integral: -

 
-$$ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx -$$ -

 
- -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. -

-
- - -
-

Statistics, moments

-
- -

-A particularly useful class of special expectation values are the -moments. The \( n \)-th moment of the PDF \( p \) is defined as -follows: -

 
-$$ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx -$$ -

 
- -The zero-th moment \( \langle 1\rangle \) is just the normalization condition of -\( p \). The first moment, \( \langle x\rangle \), is called the mean of \( p \) -and often denoted by the letter \( \mu \): -

 
-$$ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx -$$ -

 
-

-
- - -
-

Statistics, central moments

-
- -

-A special version of the moments is the set of central moments, -the n-th central moment defined as: -

 
-$$ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -$$ -

 
- -The zero-th and first central moments are both trivial, equal \( 1 \) and -\( 0 \), respectively. But the second central moment, known as the -variance of \( p \), is of particular interest. For the stochastic -variable \( X \), the variance is denoted as \( \sigma^2_X \) or \( \mathrm{var}(X) \): -

 
-$$ -\begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx -\tag{8}\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx -\tag{9}\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 -\tag{10}\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\tag{11} -\end{align} -$$ -

 
- -The square root of the variance, \( \sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle} \) is called the standard deviation of \( p \). It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the spread of \( p \) around its mean. -

-
- - -
-

Statistics, covariance

-
- -

-Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set \( \{X_i\} \) of \( n \) -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF \( P(x_1,\dots,x_n) \). The covariance of two -of the stochastic variables, \( X_i \) and \( X_j \), is defined as follows: -

 
-$$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\tag{12} -\end{align} -$$ -

 
- -with -

 
-$$ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -$$ -

 
-

-
- - -
-

Statistics, more covariance

-
- -

-If we consider the above covariance as a matrix \( C_{ij}=\mathrm{cov}(X_i,\,X_j) \), then the diagonal elements are just the familiar -variances, \( C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i) \). It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables \( X_i \) and -\( X_j \), (\( i\neq j \)): -

 
-$$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\tag{13}\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle -\tag{14}\\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle -\tag{15}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle -\tag{16}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\tag{17} -\end{align} -$$ -

 
-

-
- - -
-

Statistics, independent variables

-
- -

-If \( X_i \) and \( X_j \) are independent, we get -\( \langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle \), resulting in \( \mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j) \). - -

-Also useful for us is the covariance of linear combinations of -stochastic variables. Let \( \{X_i\} \) and \( \{Y_i\} \) be two sets of -stochastic variables. Let also \( \{a_i\} \) and \( \{b_i\} \) be two sets of -scalars. Consider the linear combination: -

 
-$$ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j -$$ -

 
- -By the linearity of the expectation value -

 
-$$ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) -$$ -

 
-

-
- - -
-

Statistics, more variance

-
- -

-Now, since the variance is just \( \mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i) \), we get -the variance of the linear combination \( U = \sum_i a_i X_i \): -

 
-$$ -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\tag{18} -\end{equation} -$$ -

 
- -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -

 
-$$ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ -

 
- -

 
-$$ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ -

 
- -which will become very useful in our study of the error in the mean -value of a set of measurements. -

-
- - -
-

Statistics and stochastic processes

-
- -

-A stochastic process is a process that produces sequentially a -chain of values: -

 
-$$ -\{x_1, x_2,\dots\,x_k,\dots\}. -$$ -

 
- -We will call these -values our measurements and the entire set as our measured -sample. The action of measuring all the elements of a sample -we will call a stochastic experiment since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF \( p_X^{\phantom X}(x) \), where \( X \) is just the formal symbol for the -stochastic variable whose PDF is \( p_X^{\phantom X}(x) \). Instead of -trying to determine the full distribution \( p \) we are often only -interested in finding the few lowest moments, like the mean -\( \mu_X^{\phantom X} \) and the variance \( \sigma_X^{\phantom X} \). -

-
- - -
-

Statistics and sample variables

-
- -

-In practical situations a sample is always of finite size. Let that -size be \( n \). The expectation value of a sample, the sample mean, is then defined as follows: -

 
-$$ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -$$ -

 
- -The sample variance is: -

 
-$$ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -$$ -

 
- -its square root being the standard deviation of the sample. The -sample covariance is: -

 
-$$ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -$$ -

 
-

-
- - -
-

Statistics, sample variance and covariance

-
- -

-Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq. (12) is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. - -

-These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean \( \mu_X \), variance \( \mathrm{var}(X) \) -and covariance \( \mathrm{cov}(X,Y) \). -

-
- - -
-

Statistics, law of large numbers

-
- -

-The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean \( \mu_X^{\phantom X} \) of the chosen PDF: -

 
-$$ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} -$$ -

 
- -The sample mean \( \bar{x}_n \) works therefore as an estimate of the true -mean \( \mu_X^{\phantom X} \). - -

-What we need to find out is how good an approximation \( \bar{x}_n \) is to -\( \mu_X^{\phantom X} \). In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the error of the sample mean, or -just sample error, and denote it by \( \mathrm{err}_X^{\phantom X} \). In -practice, we will only be able to produce an estimate of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. -

-
- - -
-

Statistics, more on sample error

-
- -

-Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements \( x_i \) -can be associated with its own stochastic variable \( X_i \). The -stochastic variable \( \overline X_n \) for the sample mean \( \bar{x}_n \) is -then just a linear combination, already familiar to us: -

 
-$$ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i -$$ -

 
- -All the coefficients are just equal \( 1/n \). The PDF of \( \overline X_n \), -denoted by \( p_{\overline X_n}(x) \) is the desired PDF of the sample -means. -

-
- - -
-

Statistics

-
- -

-The probability density of obtaining a sample mean \( \bar x_n \) -is the product of probabilities of obtaining arbitrary values \( x_1, -x_2,\dots,x_n \) with the constraint that the mean of the set \( \{x_i\} \) -is \( \bar x_n \): -

 
-$$ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 -$$ -

 
- -And in particular we are interested in its variance \( \mathrm{var}(\overline X_n) \). -

-
- - -
-

Statistics, central limit theorem

-
- -

-It is generally not possible to express \( p_{\overline X_n}(x) \) in a -closed form given an arbitrary PDF \( p_X^{\phantom X} \) and a number -\( n \). But for the limit \( n\to\infty \) it is possible to make an -approximation. The very important result is called the central limit theorem. It tells us that as \( n \) goes to infinity, -\( p_{\overline X_n}(x) \) approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, \( \mu_{X}^{\phantom X} \) -and \( \sigma_{X}^{2} \), respectively: -

 
-$$ -\begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\tag{19} -\end{equation} -$$ -

 
-

-
- - -
-

Statistics, more technicalities

-
- -

-The desired variance -\( \mathrm{var}(\overline X_n) \), i.e. the sample error squared -\( \mathrm{err}_X^2 \), is given by: -

 
-$$ -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\tag{20} -\end{equation} -$$ -

 
- -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -\( \mu_{X_i}^{\phantom X} \) of the stochastic variables \( X_i \). To -calculate these requires that we know the true multivariate PDF of all -the \( X_i \). But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the \( X_i \), estimating all properties of -\( X_i \) through the measurements of the sample. -

-
- - -
-

Statistics

-
- -

-Our estimate of \( \mu_{X_i}^{\phantom X} \) is then the sample mean \( \bar x \) -itself, in accordance with the the central limit theorem: -

 
-$$ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x -$$ -

 
- -Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an -estimate of the covariance in Eq. (20) -

 
-$$ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, -$$ -

 
- -resulting in -

 
-$$ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) -$$ -

 
-

-
- - -
-

Statistics and sample variance

-
- -

-By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables \( X_i \) -

 
-$$ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, -$$ -

 
- -which is approximated as -

 
-$$ -\begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\tag{21} -\end{equation} -$$ -

 
- -

-Now we can calculate an estimate of the error -\( \mathrm{err}_X^{\phantom X} \) of the sample mean \( \bar x_n \): -

 
-$$ -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\tag{22} -\end{align} -$$ -

 
- -which is nothing but the sample covariance divided by the number of -measurements in the sample. -

-
- - -
-

Statistics, uncorrelated results

-
- -

-In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables \( X_i \) are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: -

 
-$$ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), -$$ -

 
- -resulting in -

 
-$$ -\begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\tag{23} -\end{equation} -$$ -

 
- -where in the second step we have used Eq. (21). -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. -

-
- - -
-

Statistics, computations

-
- -

-For computational purposes one usually splits up the estimate of -\( \mathrm{err}_X^2 \), given by Eq. (22), into two -parts -

 
-$$ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), -$$ -

 
- -which equals -

 
-$$ -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) -\tag{24} -\end{equation} -$$ -

 
- -The first term is the same as the error in the uncorrelated case, -Eq. (23). This means that the second -term accounts for the error correction due to correlation between the -measurements. For uncorrelated measurements this second term is zero. -

-
- - -
-

Statistics, more on computations of errors

-
- -

-Computationally the uncorrelated first term is much easier to treat -efficiently than the second. -

 
-$$ -\mathrm{var}(x) = \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)^2 = -\left(\frac{1}{n}\sum_{k=1}^n x_k^2\right) - \bar x_n^2 -$$ -

 
- -We just accumulate separately the values \( x^2 \) and \( x \) for every -measurement \( x \) we receive. The correlation term, though, has to be -calculated at the end of the experiment since we need all the -measurements to calculate the cross terms. Therefore, all measurements -have to be stored throughout the experiment. -

-
- - -
-

Statistics, wrapping up 1

-
- -

-Let us analyze the problem by splitting up the correlation term into -partial sums of the form: -

 
-$$ -f_d = \frac{1}{n-d}\sum_{k=1}^{n-d}(x_k - \bar x_n)(x_{k+d} - \bar x_n) -$$ -

 
- -The correlation term of the error can now be rewritten in terms of -\( f_d \) -

 
-$$ -\frac{2}{n}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) = -2\sum_{d=1}^{n-1} f_d -$$ -

 
- -The value of \( f_d \) reflects the correlation between measurements -separated by the distance \( d \) in the sample samples. Notice that for -\( d=0 \), \( f \) is just the sample variance, \( \mathrm{var}(x) \). If we divide \( f_d \) -by \( \mathrm{var}(x) \), we arrive at the so called autocorrelation function -

 
-$$ -\kappa_d = \frac{f_d}{\mathrm{var}(x)} -$$ -

 
- -which gives us a useful measure of pairwise correlations -starting always at \( 1 \) for \( d=0 \). -

-
- - -
-

Statistics, final expression

-
- -

-The sample error (see eq. (24)) can now be -written in terms of the autocorrelation function: -

 
-$$ -\begin{align} -\mathrm{err}_X^2 &= -\frac{1}{n}\mathrm{var}(x)+\frac{2}{n}\cdot\mathrm{var}(x)\sum_{d=1}^{n-1} -\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=& -\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\ -&=\frac{\tau}{n}\cdot\mathrm{var}(x) -\tag{25} -\end{align} -$$ -

 
- -and we see that \( \mathrm{err}_X \) can be expressed in terms the -uncorrelated sample variance times a correction factor \( \tau \) which -accounts for the correlation between measurements. We call this -correction factor the autocorrelation time: -

 
-$$ -\begin{equation} -\tau = 1+2\sum_{d=1}^{n-1}\kappa_d -\tag{26} -\end{equation} -$$ -

 
-

-
- - -
-

Statistics, effective number of correlations

-
- -

-For a correlation free experiment, \( \tau \) -equals 1. From the point of view of -eq. (25) we can interpret a sequential -correlation as an effective reduction of the number of measurements by -a factor \( \tau \). The effective number of measurements becomes: -

 
-$$ -n_\mathrm{eff} = \frac{n}{\tau} -$$ -

 
- -To neglect the autocorrelation time \( \tau \) will always cause our -simple uncorrelated estimate of \( \mathrm{err}_X^2\approx \mathrm{var}(x)/n \) to -be less than the true sample error. The estimate of the error will be -too good. On the other hand, the calculation of the full -autocorrelation time poses an efficiency problem if the set of -measurements is very large. -

-
- - -
-

Linking the regression analysis with a statistical interpretation

- -

-Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. -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. - -

-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 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 \). -

- - -
-

Assumptions made

- -

-The assumption we have made here can be summarized as (and this is going to 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 describes our data -

 
-$$ -\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}. -$$ -

 
-

- - -
-

Expectation value and variance

- -

-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 -

 
-$$ -\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). -

- - -
-

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

- -

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

 
-$$ -\mathbb{E}(\boldsymbol{\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}. -$$ -

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

-We can also calculate the variance - -

-The variance of \( \boldsymbol{\beta} \) is -

 
-$$ -\begin{eqnarray*} -\mbox{Var}(\boldsymbol{\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: -\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{ -[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to -construct a confidence interval for the estimates. - -

-In a similar way, we cna obtain analytical expressions for say the -expectation values of the parameters \( \boldsymbol{\beta} \) and their variance -when we employ Ridge regression, and thereby 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 - -

 
-$$ -\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. -

- - -
-

Cross-validation

- -

-Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e. the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. - -

-The setting of original and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the -training set, plays the role of original data on which the model is -built. The second of these data sets, called the test set, plays the -role of the novel data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of \( \lambda \) using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. -

- - -
-

Computationally expensive

- -

-The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: - -

    -

  • The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set.
  • -

  • In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set.
  • -
-
- - -
-

Various steps in cross-validation

- -

-When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this \( k \)-fold cross-validation structures the data splitting. The -samples are divided into \( k \) more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the \( k \) subsets -involves a degree of randomness. This may be fully excluded when -choosing \( k=n \). This particular case is referred to as leave-one-out -cross-validation (LOOCV). -

- - -
-

How to set up the cross-validation for Ridge and/or Lasso

- -
    -

  • Define a range of interest for the penalty parameter.
  • -

  • Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
  • -

  • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as
  • -
-

 
-$$ -\begin{align*} -\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} -\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} -\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} -\end{align*} -$$ -

 
- - -

    -

  • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
  • -

  • Repeat the first three steps such that each sample plays the role of the test set once.
  • -

  • Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the cross-validated log-likelihood. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
  • -
-

 
-$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ -

 
- - -

    -

  • The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions.
  • -
-
- - -
-

Resampling methods: Jackknife and Bootstrap

- -

-Two famous -resampling methods are the independent bootstrap and the jackknife. - -

-The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as the dependent bootstrap. - -

-The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of \( \overline{X} \) (which often is the case), then there is no -need for bootstrapping. -

- - -
-

Resampling methods: Jackknife

- -

-The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \boldsymbol{x}_i \) denote the vector -

 
-$$ -\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ -

 
- -

-which equals the vector \( \boldsymbol{x} \) with the exception that observation -number \( i \) is left out. Using this notation, define -\( \widehat{\theta}_i \) to be the estimator -\( \widehat{\theta} \) computed using \( \vec{X}_i \). -

- - -
-

Jackknife code example

-

- - -

from numpy import *
-from numpy.random import randint, randn
-from time import time
-
-def jackknife(data, stat):
-    n = len(data);t = zeros(n); inds = arange(n); t0 = time()
-    ## 'jackknifing' by leaving out an observation for each i                                                                                                                      
-    for i in range(n):
-        t[i] = stat(delete(data,i) )
-
-    # analysis                                                                                                                                                                     
-    print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
-    print("original           bias      std. error")
-    print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
-
-    return t
-
-
-# Returns mean of data samples                                                                                                                                                     
-def stat(data):
-    return mean(data)
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# jackknife returns the data sample                                                                                                                                                
-t = jackknife(x, stat)
-
-
- - -
-

Resampling methods: Bootstrap

-
- -

-Bootstrapping is a nonparametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: - -

    -

  1. The bootstrap is quite general, although there are some cases in which it fails.
  2. - -

  3. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
  4. - -

  5. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
  6. -

  7. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
  8. -
-
-
- - -
-

Resampling methods: Bootstrap background

- -

-Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, -\( \widehat{\theta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to -estimate \( p(\boldsymbol{t}) \) by the relative frequency of -\( \widehat{\theta} \). You can think of this as using a histogram -in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely -resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point -estimators. -

- - -
-

Resampling methods: More Bootstrap background

- -

-In the case that \( \widehat{\theta} \) has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of \( X_i \), \( p(x) \), had been known, then it would have -been straight forward to do this by: - -

    -

  1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
  2. -

  3. Then using these numbers, we could compute a replica of \( \widehat{\theta} \) called \( \widehat{\theta}^* \).
  4. -
-

- -By repeated use of (1) and (2), many -estimates of \( \widehat{\theta} \) could have been obtained. The -idea is to use the relative frequency of \( \widehat{\theta}^* \) -(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). -

- - -
-

Resampling methods: Bootstrap approach

- -

-But -unless there is enough information available about the process that -generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general -unknown. Therefore, Efron in 1979 asked the -question: What if we replace \( p(x) \) by the relative frequency -of the observation \( X_i \); if we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - -

-Instead of generating the histogram for the relative -frequency of the observation \( X_i \), just draw the values -\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector -\( \boldsymbol{X} \). -

- - -
-

Resampling methods: Bootstrap steps

- -

-The independent bootstrap works like this: - -

    -

  1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
  2. -

  3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
  4. -

  5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
  6. -

  7. Repeat this process \( k \) times.
  8. -
-

- -When you are done, you can draw a histogram of the relative frequency -of \( \widehat \theta^* \). This is your estimate of the probability -distribution \( p(t) \). Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of \( \widehat{\theta}^* \). Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of \( \widehat -\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values -\( \widehat \theta ^* \). -

- - -
-

Code example for the Bootstrap method

- -

-The following code starts with a Gaussian distribution with mean value -\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data -used in the bootstrap analysis. The bootstrap analysis returns a data -set after a given number of bootstrap operations (as many as we have -data points). This data set consists of estimated mean values for each -bootstrap operation. The histogram generated by the bootstrap method -shows that the distribution for these mean values is also a Gaussian, -centered around the mean value \( \mu=100 \) but with standard deviation -\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in -this case the same as the number of original data points). The value -of the standard deviation is what we expect from the central limit -theorem. - -

- - -

from numpy import *
-from numpy.random import randint, randn
-from time import time
-import matplotlib.mlab as mlab
-import matplotlib.pyplot as plt
-
-# Returns mean of bootstrap samples                                                                                                                                                
-def stat(data):
-    return mean(data)
-
-# Bootstrap algorithm
-def bootstrap(data, statistic, R):
-    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
-    # non-parametric bootstrap         
-    for i in range(R):
-        t[i] = statistic(data[randint(0,n,n)])
-
-    # analysis    
-    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
-    print("original           bias      std. error")
-    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
-    return t
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# bootstrap returns the data sample                                    
-t = bootstrap(x, stat, datapoints)
-# the histogram of the bootstrapped  data                                                                                                    
-n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
-
-# add a 'best fit' line  
-y = mlab.normpdf( binsboot, mean(t), std(t))
-lt = plt.plot(binsboot, y, 'r--', linewidth=1)
-plt.xlabel('Smarts')
-plt.ylabel('Probability')
-plt.axis([99.5, 100.6, 0, 3.0])
-plt.grid(True)
-
-plt.show()
-
-
- - -
-

Code Example for Cross-validation and \( k \)-fold Cross-validation

- -

-The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.model_selection import KFold
-from sklearn.linear_model import Ridge
-from sklearn.model_selection import cross_val_score
-from sklearn.preprocessing import PolynomialFeatures
-
-# A seed just to ensure that the random numbers are the same for every run.
-# Useful for eventual debugging.
-np.random.seed(3155)
-
-# Generate the data.
-nsamples = 100
-x = np.random.randn(nsamples)
-y = 3*x**2 + np.random.randn(nsamples)
-
-## Cross-validation on Ridge regression using KFold only
-
-# Decide degree on polynomial to fit
-poly = PolynomialFeatures(degree = 6)
-
-# Decide which values of lambda to use
-nlambdas = 500
-lambdas = np.logspace(-3, 5, nlambdas)
-
-# Initialize a KFold instance
-k = 5
-kfold = KFold(n_splits = k)
-
-# Perform the cross-validation to estimate MSE
-scores_KFold = np.zeros((nlambdas, k))
-
-i = 0
-for lmb in lambdas:
-    ridge = Ridge(alpha = lmb)
-    j = 0
-    for train_inds, test_inds in kfold.split(x):
-        xtrain = x[train_inds]
-        ytrain = y[train_inds]
-
-        xtest = x[test_inds]
-        ytest = y[test_inds]
-
-        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
-        ridge.fit(Xtrain, ytrain[:, np.newaxis])
-
-        Xtest = poly.fit_transform(xtest[:, np.newaxis])
-        ypred = ridge.predict(Xtest)
-
-        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
-
-        j += 1
-    i += 1
-
-
-estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
-
-## Cross-validation using cross_val_score from sklearn along with KFold
-
-# kfold is an instance initialized above as:
-# kfold = KFold(n_splits = k)
-
-estimated_mse_sklearn = np.zeros(nlambdas)
-i = 0
-for lmb in lambdas:
-    ridge = Ridge(alpha = lmb)
-
-    X = poly.fit_transform(x[:, np.newaxis])
-    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
-
-    # cross_val_score return an array containing the estimated negative mse for every fold.
-    # we have to the the mean of every array in order to get an estimate of the mse of the model
-    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
-
-    i += 1
-
-## Plot and compare the slightly different ways to perform cross-validation
-
-plt.figure()
-
-plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
-plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
-
-plt.xlabel('log10(lambda)')
-plt.ylabel('mse')
-
-plt.legend()
-
-plt.show()
-
-
- - -
-

The bias-variance tradeoff

- -

-We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset \( \mathcal{L} \) consisting of the data -\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). - -

-Let us assume that the true data is generated from a noisy model - -

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

 
- -

-where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). - -

-In our derivation of the ordinary least squares method we defined then -an approximation to the function \( f \) in terms of the parameters -\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, -that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). - -

-Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function -

 
-$$ -C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. -$$ -

 
- -

-We can rewrite this as -

 
-$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2. -$$ -

 
- -

-The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error \( \boldsymbol{\epsilon} \). - -

-To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). -We use a more compact notation in terms of the expectation value -

 
-$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], -$$ -

 
- -and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get -

 
-$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], -$$ -

 
- -which, using the abovementioned expectation values can be rewritten as -

 
-$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, -$$ -

 
- -that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \). -

- - -
-

Example code for Bias-Variance tradeoff

-

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-
-np.random.seed(2018)
-
-n = 500
-n_boostraps = 100
-degree = 18  # A quite high value, just to show.
-noise = 0.1
-
-# Make data set.
-x = np.linspace(-1, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
-
-# Hold out some test data that is never used in training.
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-# Combine x transformation and model into one operation.
-# Not neccesary, but convenient.
-model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
-
-# The following (m x n_bootstraps) matrix holds the column vectors y_pred
-# for each bootstrap iteration.
-y_pred = np.empty((y_test.shape[0], n_boostraps))
-for i in range(n_boostraps):
-    x_, y_ = resample(x_train, y_train)
-
-    # Evaluate the new model on the same test data each time.
-    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
-# Note: Expectations and variances taken w.r.t. different training
-# data sets, hence the axis=1. Subsequent means are taken across the test data
-# set in order to obtain a total value, but before this we have error/bias/variance
-# calculated per data point in the test set.
-# Note 2: The use of keepdims=True is important in the calculation of bias as this 
-# maintains the column vector form. Dropping this yields very unexpected results.
-error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
-bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
-variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
-print('Error:', error)
-print('Bias^2:', bias)
-print('Var:', variance)
-print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
-
-plt.plot(x[::5, :], y[::5, :], label='f(x)')
-plt.scatter(x_test, y_test, label='Data points')
-plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
-plt.legend()
-plt.show()
-
-
- - -
-

Understanding what happens

-

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-
-np.random.seed(2018)
-
-n = 40
-n_boostraps = 100
-maxdegree = 14
-
-
-# Make data set.
-x = np.linspace(-3, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
-error = np.zeros(maxdegree)
-bias = np.zeros(maxdegree)
-variance = np.zeros(maxdegree)
-polydegree = np.zeros(maxdegree)
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-for degree in range(maxdegree):
-    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
-    y_pred = np.empty((y_test.shape[0], n_boostraps))
-    for i in range(n_boostraps):
-        x_, y_ = resample(x_train, y_train)
-        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
-    polydegree[degree] = degree
-    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
-    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
-    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
-    print('Polynomial degree:', degree)
-    print('Error:', error[degree])
-    print('Bias^2:', bias[degree])
-    print('Var:', variance[degree])
-    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-
-plt.plot(polydegree, np.log10(error), label='Error')
-plt.plot(polydegree, bias, label='bias')
-plt.plot(polydegree, variance, label='Variance')
-plt.legend()
-plt.show()
-
-
- - -
-

Summing up

- -

-The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - -

-The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below \( Var(\epsilon) \), the irreducible error. - -

-What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. -

- - -
-

Another Example rom Scikit-Learn's Repository

-

- - -

"""
-============================
-Underfitting vs. Overfitting
-============================
-
-This example demonstrates the problems of underfitting and overfitting and
-how we can use linear regression with polynomial features to approximate
-nonlinear functions. The plot shows the function that we want to approximate,
-which is a part of the cosine function. In addition, the samples from the
-real function and the approximations of different models are displayed. The
-models have polynomial features of different degrees. We can see that a
-linear function (polynomial with degree 1) is not sufficient to fit the
-training samples. This is called **underfitting**. A polynomial of degree 4
-approximates the true function almost perfectly. However, for higher degrees
-the model will **overfit** the training data, i.e. it learns the noise of the
-training data.
-We evaluate quantitatively **overfitting** / **underfitting** by using
-cross-validation. We calculate the mean squared error (MSE) on the validation
-set, the higher, the less likely the model generalizes correctly from the
-training data.
-"""
-
-print(__doc__)
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.pipeline import Pipeline
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.linear_model import LinearRegression
-from sklearn.model_selection import cross_val_score
-
-
-def true_fun(X):
-    return np.cos(1.5 * np.pi * X)
-
-np.random.seed(0)
-
-n_samples = 30
-degrees = [1, 4, 15]
-
-X = np.sort(np.random.rand(n_samples))
-y = true_fun(X) + np.random.randn(n_samples) * 0.1
-
-plt.figure(figsize=(14, 5))
-for i in range(len(degrees)):
-    ax = plt.subplot(1, len(degrees), i + 1)
-    plt.setp(ax, xticks=(), yticks=())
-
-    polynomial_features = PolynomialFeatures(degree=degrees[i],
-                                             include_bias=False)
-    linear_regression = LinearRegression()
-    pipeline = Pipeline([("polynomial_features", polynomial_features),
-                         ("linear_regression", linear_regression)])
-    pipeline.fit(X[:, np.newaxis], y)
-
-    # Evaluate the models using crossvalidation
-    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
-                             scoring="neg_mean_squared_error", cv=10)
-
-    X_test = np.linspace(0, 1, 100)
-    plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
-    plt.plot(X_test, true_fun(X_test), label="True function")
-    plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
-    plt.xlabel("x")
-    plt.ylabel("y")
-    plt.xlim((0, 1))
-    plt.ylim((-2, 2))
-    plt.legend(loc="best")
-    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
-        degrees[i], -scores.mean(), scores.std()))
-plt.show()
-
-
- - -
-

The one-dimensional Ising model

- -

-Let us bring back the Ising model again, but now with an additional -focus on Ridge and Lasso regression as well. We repeat some of the -basic parts of the Ising model and the setup of the training and test -data. The one-dimensional Ising model with nearest neighbor -interaction, no external field and a constant coupling constant \( J \) is -given by - -

 
-$$ -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\tag{27} -\end{align} -$$ -

 
- -where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins in the system is determined by \( L \). For the one-dimensional system there is no phase transition. - -

-We will look at a system of \( L = 40 \) spins with a coupling constant of \( J = 1 \). To get enough training data we will generate 10000 states with their respective energies. - -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from mpl_toolkits.axes_grid1 import make_axes_locatable
-import seaborn as sns
-import scipy.linalg as scl
-from sklearn.model_selection import train_test_split
-import sklearn.linear_model as skl
-import tqdm
-sns.set(color_codes=True)
-cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
-
-L = 40
-n = int(1e4)
-
-spins = np.random.choice([-1, 1], size=(n, L))
-J = 1.0
-
-energies = np.zeros(n)
-
-for i in range(n):
-    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-
-

-A more general form for the one-dimensional Ising model is - -

 
-$$ -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\tag{28} -\end{align} -$$ -

 
- -

-Here we allow for interactions beyond the nearest neighbors and a more -adaptive coupling matrix. This latter expression can be formulated as -a matrix-product on the form -

 
-$$ -\begin{align} - H = X J, -\tag{29} -\end{align} -$$ -

 
- -

-where \( X_{jk} = s_j s_k \) and \( J \) is the matrix consisting of the -elements \( -J_{jk} \). This form of writing the energy fits perfectly -with the form utilized in linear regression, viz. -

 
-$$ -\begin{align} - \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}. -\tag{30} -\end{align} -$$ -

 
- -We organize the data as we did above -

- - -

X = np.zeros((n, L ** 2))
-for i in range(n):
-    X[i] = np.outer(spins[i], spins[i]).ravel()
-y = energies
-X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)
-
-X_train_own = np.concatenate(
-    (np.ones(len(X_train))[:, np.newaxis], X_train),
-    axis=1
-)
-
-X_test_own = np.concatenate(
-    (np.ones(len(X_test))[:, np.newaxis], X_test),
-    axis=1
-)
-
-

-We will do all fitting with Scikit-Learn, - -

- - -

clf = skl.LinearRegression().fit(X_train, y_train)
-
-

-When extracting the \( J \)-matrix we make sure to remove the intercept -

- - -

J_sk = clf.coef_.reshape(L, L)
-
-

-And then we plot the results -

- - -

fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_sk, **cmap_args)
-plt.title("LinearRegression from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-plt.show()
-
-

-The results perfectly with our previous discussion where we used our own code. -

- - -
-

Ridge regression

- -

-Having explored the ordinary least squares we move on to ridge -regression. In ridge regression we include a regularizer. This -involves a new cost function which leads to a new estimate for the -weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The -cost function is given by - -

 
-$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}. -\tag{31} -\end{align} -$$ -

 
- -

- - -

_lambda = 0.1
-clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
-J_ridge_sk = clf_ridge.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_ridge_sk, **cmap_args)
-plt.title("Ridge from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-plt.show()
-
-
- - -
-

LASSO regression

- -

-In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function. - -

 
-$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}. -\tag{32} -\end{align} -$$ -

 
- -

-Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn. - -

- - -

clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)
-J_lasso_sk = clf_lasso.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_lasso_sk, **cmap_args)
-plt.title("Lasso from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-plt.show()
-
-

-It is quite striking how LASSO breaks the symmetry of the coupling -constant as opposed to ridge and OLS. We get a sparse solution with -\( J_{j, j + 1} = -1 \). -

- - -
-

Performance as function of the regularization parameter

- -

-We see how the different models perform for a different set of values for \( \lambda \). - -

- - -

lambdas = np.logspace(-4, 5, 10)
-
-train_errors = {
-    "ols_sk": np.zeros(lambdas.size),
-    "ridge_sk": np.zeros(lambdas.size),
-    "lasso_sk": np.zeros(lambdas.size)
-}
-
-test_errors = {
-    "ols_sk": np.zeros(lambdas.size),
-    "ridge_sk": np.zeros(lambdas.size),
-    "lasso_sk": np.zeros(lambdas.size)
-}
-
-plot_counter = 1
-
-fig = plt.figure(figsize=(32, 54))
-
-for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
-    for key, method in zip(
-        ["ols_sk", "ridge_sk", "lasso_sk"],
-        [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
-    ):
-        method = method.fit(X_train, y_train)
-
-        train_errors[key][i] = method.score(X_train, y_train)
-        test_errors[key][i] = method.score(X_test, y_test)
-
-        omega = method.coef_.reshape(L, L)
-
-        plt.subplot(10, 5, plot_counter)
-        plt.imshow(omega, **cmap_args)
-        plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda))
-        plot_counter += 1
-
-plt.show()
-
-

-We see that LASSO reaches a good solution for low -values of \( \lambda \), but will "wither" when we increase \( \lambda \) too -much. Ridge is more stable over a larger range of values for -\( \lambda \), but eventually also fades away. -

- - -
-

Finding the optimal value of \( \lambda \)

- -

-To determine which value of \( \lambda \) is best we plot the accuracy of -the models when predicting the training and the testing set. We expect -the accuracy of the training set to be quite good, but if the accuracy -of the testing set is much lower this tells us that we might be -subject to an overfit model. The ideal scenario is an accuracy on the -testing set that is close to the accuracy of the training set. - -

- - -

fig = plt.figure(figsize=(20, 14))
-
-colors = {
-    "ols_sk": "r",
-    "ridge_sk": "y",
-    "lasso_sk": "c"
-}
-
-for key in train_errors:
-    plt.semilogx(
-        lambdas,
-        train_errors[key],
-        colors[key],
-        label="Train {0}".format(key),
-        linewidth=4.0
-    )
-
-for key in test_errors:
-    plt.semilogx(
-        lambdas,
-        test_errors[key],
-        colors[key] + "--",
-        label="Test {0}".format(key),
-        linewidth=4.0
-    )
-plt.legend(loc="best", fontsize=18)
-plt.xlabel(r"$\lambda$", fontsize=18)
-plt.ylabel(r"$R^2$", fontsize=18)
-plt.tick_params(labelsize=18)
-plt.show()
-
-

-From the above figure we can see that LASSO with \( \lambda = 10^{-2} \) -achieves a very good accuracy on the test set. This by far surpasses the -other models for all values of \( \lambda \). -

- - -
-

Further Exercises

- -

Exercise 1

- -

-We will 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,1)
-y = 5*x*x+0.1*np.random.randn(100,1)
-
-
    -

  1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial.
  2. -

  3. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
  4. - -

  5. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  6. -
-

 
-$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ -

 
- -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -

 
-$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ -

 
- -where we have defined the mean value of \( \hat{y} \) as -

 
-$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ -

 
- -

-You can use the functionality included in scikit-learn. If you feel -for it, you can use your own program and define functions which -compute the above two functions. Discuss the meaning of these -results. Try also to vary the coefficient in front of the added -stochastic noise term and discuss the quality of the fits. - -

Exercise 2, variance of the parameters \( \beta \) in linear regression

- -

-Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as - -

 
-$$ -\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, -$$ -

 
- -with -

 
-$$ -\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, -$$ -

 
- -where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)). - -

Exercise 3

- -

-This exercise is a continuation of exercise 1. 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. You can use the code under the Regression as an example on how to use the Ridge and the Lasso 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,1)
-y = 5*x*x+0.1*np.random.randn(100,1)
-
-
    -

  1. Write your own code for the Ridge method and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 1. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
  2. -

  3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
  4. -

  5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing 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 that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions
  6. -

  7. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.
  8. -

  9. Try to implement the cross-validation as well.
  10. -

  11. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  12. -
-

 
-$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ -

 
- -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -

 
-$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ -

 
- -where we have defined the mean value of \( \hat{y} \) as -

 
-$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ -

 
- -Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. - -

Exercise 4

- -

-We will study how -to fit polynomials to a specific two-dimensional function called -Franke's -function. This -is a function which has been widely used when testing various interpolation and fitting -algorithms. Furthermore, after having established the model and the -method, we will employ resamling techniques such as the cross-validation and/or -the bootstrap methods, in order to perform a proper assessment of our models. - -

-The Franke function, which is a weighted sum of four exponentials reads as follows -

 
-$$ -\begin{align*} -f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ -&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. -\end{align*} -$$ -

 
- -

-The function will be defined for \( x,y\in [0,1] \). Our first step will -be to perform an OLS regression analysis of this function, trying out -a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y, -x^2, y^2, xy, \dots] \). We will also include cross-validation and -bootstrap as resampling techniques. As in homeworks 1 and 2, we -can use a uniform distribution to set up the arrays of values for \( x \) -and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size. -In this case we will have two predictors and need to fit a -function (for example a polynomial) of \( x \) and \( y \). Thereafter we will -repeat much of the same procedure using the the Ridge and -Lasso regression methods, introducing thus a dependence on the bias -(penalty) \( \lambda \). - -

-The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) -

- - -

from mpl_toolkits.mplot3d import Axes3D
-import matplotlib.pyplot as plt
-from matplotlib import cm
-from matplotlib.ticker import LinearLocator, FormatStrFormatter
-import numpy as np
-from random import random, seed
-
-fig = plt.figure()
-ax = fig.gca(projection='3d')
-
-# Make data.
-x = np.arange(0, 1, 0.05)
-y = np.arange(0, 1, 0.05)
-x, y = np.meshgrid(x,y)
-
-
-def FrankeFunction(x,y):
-    term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-    term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-    term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-    term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-    return term1 + term2 + term3 + term4
-
-
-z = FrankeFunction(x, y)
-
-# Plot the surface.
-surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
-                       linewidth=0, antialiased=False)
-
-# Customize the z axis.
-ax.set_zlim(-0.10, 1.40)
-ax.zaxis.set_major_locator(LinearLocator(10))
-ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
-
-# Add a color bar which maps values to colors.
-fig.colorbar(surf, shrink=0.5, aspect=5)
-
-plt.show()
-
-

-We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where -\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform -distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition -an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). - -

-Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3 -and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) -

 
-$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ -

 
- -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -

 
-$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ -

 
- -where we have defined the mean value of \( \hat{y} \) as -

 
-$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ -

 
- -

-Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm -and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models. - -

-Write then your own code for the Ridge method, either using matrix -inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the -previous exercise (for the same polynomials and include resampling -techniques) but now for different values of \( \lambda \). Compare and -analyze your results with those obtained with standard OLS. Study the -dependence on \( \lambda \) while also varying eventually the strength of -the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). - -

-Then perform the same studies but now with Lasso regression. Use the functionalities of -scikit-learn. Give a critical discussion of the three methods and a -judgement of which model fits the data best. -

- - - -
-
- - - - - - - - - - - - diff --git a/doc/src/Regression/Regression-solarized.html b/doc/src/Regression/Regression-solarized.html deleted file mode 100644 index 6d7cff2dc..000000000 --- a/doc/src/Regression/Regression-solarized.html +++ /dev/null @@ -1,4279 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis

- -

- - -

-Morten Hjorth-Jensen [1, 2] -
- -

- - -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

-

Jul 22, 2019

-
-

-









- -

Why Linear Regression (aka Ordinary Least Squares and family)

- -

-Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \). - -

- -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. - -

-









- -

Regression analysis, overarching aims

-
- -

- -

-Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. - -

-A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with - -

- - The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. -
- - -

-









- -

Regression analysis, overarching aims II

-
- -

- -

-Consider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix -\( \mathbf{X} \). - -

-The matrix \( \mathbf{X} \) is called the design -matrix. Additional information of the samples is available in the -form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is -generally referred to as the response variable. The aim of -regression analysis is to explain \( \boldsymbol{y} \) in terms of -\( \boldsymbol{X} \) through a functional relationship like \( y_i = -f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of -\( f(\cdot) \) is available, it is common to assume a linear relationship -between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to -the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T} \) are the regression parameters. - -

-Linear regression gives us a set of analytical equations for the parameters \( \beta_j \). - - -

- - -

-









- -

Examples

-
- -

-In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), -consider the model we discussed for describing nuclear binding energies. - -

-There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. -Assuming -$$ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, -$$ - -we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. -This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a -\( p\times n \) matrix \( \boldsymbol{X} \). - -

-Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \) - - -

- - -

-









- -

General linear models

-
- -

-Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. - -

-Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is -$$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, -$$ - -where \( \epsilon_i \) is the error in our approximation. - - -

- - -

-









- -

Rewriting the fitting procedure as a linear algebra problem

-
- -

-For every set of values \( y_i,x_i \) we have thus the corresponding set of equations -$$ -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ -

- - -

-









- -

Rewriting the fitting procedure as a linear algebra problem, more details

-
- -

-Defining the vectors -$$ -\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -$$ - -and -$$ -\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -$$ - -and -$$ -\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -$$ - -and the design matrix -$$ -\boldsymbol{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -$$ - -we can rewrite our equations as -$$ -\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. -$$ - -The above design matrix is called a Vandermonde matrix. -

- - -

-









- -

Generalizing the fitting procedure as a linear algebra problem

-
- -

- -

-We are obviously not limited to the above polynomial expansions. We -could replace the various powers of \( x \) with elements of Fourier -series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j -x_i)} \), or time series or other orthogonal functions. For every set -of values \( y_i,x_i \) we can then generalize the equations to - -$$ -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ - -

-Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case! -

- - -

-









- -

Generalizing the fitting procedure as a linear algebra problem

-
- -

-We redefine in turn the matrix \( \boldsymbol{X} \) as -$$ -\boldsymbol{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -$$ - -and without loss of generality we rewrite again our equations as -$$ -\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. -$$ - -The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? -

- - -

-









- -

Optimizing our parameters

-
- -

-We have defined the matrix \( \boldsymbol{X} \) via the equations -$$ -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ - -

-As we noted above, we stayed with a system with the design matrix - \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define -our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. - - -

- - -

-









- -

Our model for the nuclear binding energies

- -

-In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. - -

-We restate the parts of the code we are most interested in. -

- - -

# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("MassEval2016.dat"),'r')
-
-
-# Read the experimental data with Pandas
-Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
-              names=('N', 'Z', 'A', 'Element', 'Ebinding'),
-              widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
-              header=39,
-              index_col=False)
-
-# Extrapolated values are indicated by '#' in place of the decimal place, so
-# the Ebinding column won't be numeric. Coerce to float and drop these entries.
-Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
-Masses = Masses.dropna()
-# Convert from keV to MeV.
-Masses['Ebinding'] /= 1000
-
-# Group the DataFrame by nucleon number, A.
-Masses = Masses.groupby('A')
-# Find the rows of the grouped DataFrame with the maximum binding energy.
-Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
-A = Masses['A']
-Z = Masses['Z']
-N = Masses['N']
-Element = Masses['Element']
-Energies = Masses['Ebinding']
-
-# Now we set up the design matrix X
-X = np.zeros((len(A),5))
-X[:,0] = 1
-X[:,1] = A
-X[:,2] = A**(2.0/3.0)
-X[:,3] = A**(-1.0/3.0)
-X[:,4] = A**(-1.0)
-# Then nice printout using pandas
-DesignMatrix = pd.DataFrame(X)
-DesignMatrix.index = A
-DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
-display(DesignMatrix)
-
-

-With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as -$$ -\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, -$$ - -throughout these lectures. - -

-









- -

Optimizing our parameters, more details

-
- -

-With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as -$$ -\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, -$$ - -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely -$$ -C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, -$$ - -or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as -$$ -C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}. -$$ - -This function is one possible way to define the so-called cost function. - -

-It is also common to define -the function \( Q \) as - -$$ -C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, -$$ - -since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out. -

- - -

-









- -

Interpretations and optimizing our parameters

-
- -

- -

-The function -$$ -C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, -$$ - -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) -$$ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -$$ - -

-where \( \langle y_i \rangle \) is the mean value. Keep in mind also that -till now we have treated \( y_i \) as the exact value. Normally, the -response (dependent or outcome) variable \( y_i \) the outcome of a -numerical experiment or another type of experiment and is thus only an -approximation to the true value. It is then always accompanied by an -error estimate, often limited to a statistical error estimate given by -the standard deviation discussed earlier. In the discussion here we -will treat \( y_i \) as our exact value for the response variable. - -

-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem -$$ -{\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\}. -$$ - -In practical terms it means we will require -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -$$ - -which results in -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -$$ - -or in a matrix-vector form as -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). -$$ - - -

- - -

-









- -

Interpretations and optimizing our parameters

-
- -

-We can rewrite -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), -$$ - -as -$$ -\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, -$$ - -and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution -$$ -\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ - -

-We note also that since our design matrix is defined as \( \boldsymbol{X}\in -{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in -{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), -in our case \( p=5 \) meaning that we end up with inverting a small -\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional -matrices to invert. The methods discussed here and for many other -supervised learning algorithms like classification with logistic -regression or support vector machines, exhibit dimensionalities which -allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \). - - -

- - -

-









- -

Interpretations and optimizing our parameters

-
- -

-The residuals \( \boldsymbol{\epsilon} \) are in turn given by -$$ -\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, -$$ - -and with -$$ -\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, -$$ - -we have -$$ -\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, -$$ - -meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. - - -

- - -

-Let us now return to our nuclear binding energies and simply code the above equations. - -

-









- -

Own code for Ordinary Least Squares

- -

-It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to -write -

- - -

# matrix inversion to find beta
-beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
-# and then make the prediction
-ytilde = X @ beta
-
-

-Alternatively, you can use the least squares functionality in Numpy as -

- - -

fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
-ytildenp = np.dot(fit,X.T)
-
-

-And finally we plot our fit with and compare with data -

- - -

Masses['Eapprox']  = ytilde
-# Generate a plot comparing the experimental with the fitted values values.
-fig, ax = plt.subplots()
-ax.set_xlabel(r'$A = N + Z$')
-ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
-ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
-            label='Ame2016')
-ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
-            label='Fit')
-ax.legend()
-save_fig("Masses2016OLS")
-plt.show()
-
-

-









- -

Adding error analysis and training set up

- -

-We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. -Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as -

- - -

def R2(y_data, y_model):
-    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
-
-

-and we would be using it as -

- - -

print(R2(Energies,ytilde))
-
-

-We can easily add our MSE score as -

- - -

def MSE(y_data,y_model):
-    n = np.size(y_model)
-    return np.sum((y_data-y_model)**2)/n
-
-print(MSE(Energies,ytilde))
-
-

-and finally the relative error as -

- - -

def RelativeError(y_data,y_model):
-    return abs((y_data-y_model)/y_data)
-print(RelativeError(Energies, ytilde))
-
-

-









- -

The \( \chi^2 \) function

-
- -

- -

-Normally, the response (dependent or outcome) variable \( y_i \) is the -outcome of a numerical experiment or another type of experiment and is -thus only an approximation to the true value. It is then always -accompanied by an error estimate, often limited to a statistical error -estimate given by the standard deviation discussed earlier. In the -discussion here we will treat \( y_i \) as our exact value for the -response variable. - -

-Introducing the standard deviation \( \sigma_i \) for each measurement -\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) -as - -$$ -\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, -$$ - -where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - - -

- - -

-









- -

The \( \chi^2 \) function

-
- -

- -

-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -$$ - -which results in -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -$$ - -or in a matrix-vector form as -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). -$$ - -where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \). -

- - -

-









- -

The \( \chi^2 \) function

-
- -

- -

-We can rewrite -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), -$$ - -as -$$ -\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, -$$ - -and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution -$$ -\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. -$$ -

- - -

-









- -

The \( \chi^2 \) function

-
- -

- -

-If we then introduce the matrix -$$ -\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, -$$ - -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) -$$ -\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} -$$ - -We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise) -$$ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -$$ - -resulting in -$$ -\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! -$$ -

- - -

-









- -

The \( \chi^2 \) function

-
- -

-The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write -$$ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -$$ - -By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -$$ - -and -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -$$ -

- - -

-









- -

The \( \chi^2 \) function

-
- -

- -

-For a linear fit (a first-order polynomial) we don't need to invert a matrix!! -Defining -$$ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -$$ - - -$$ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -$$ - - -$$ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -$$ - - -$$ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -$$ - - -$$ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -$$ - -

-we obtain - -$$ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -$$ - - -$$ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -$$ - -

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

- - -

-









- -

Fitting an Equation of State for Dense Nuclear Matter

- -

-Before we continue, let us introduce yet another example. We are going to fit the -nuclear equation of state using results from many-body calculations. -The equation of state we have made available here, as function of -density, has been derived using modern nucleon-nucleon potentials with -the addition of three-body -forces. This -time the file is presented as a standard csv file. - -

-The beginning of the Python code here is similar to what you have seen before, -with the same initializations and declarations. We use also pandas -again, rather extensively in order to organize our data. - -

-The difference now is that we use Scikit-Learn's regression tools -instead of our own matrix inversion implementation. Furthermore, we -sneak in Ridge regression (to be discussed below) which includes a -hyperparameter \( \lambda \), also to be explained below. - -

-









- -

The code

- -

- - -

# Common imports
-import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-import matplotlib.pyplot as plt
-import sklearn.linear_model as skl
-from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as  csv file and organize the data into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-#  The design matrix now as function of various polytrops
-X = np.zeros((len(Density),4))
-X[:,3] = Density**(4.0/3.0)
-X[:,2] = Density
-X[:,1] = Density**(2.0/3.0)
-X[:,0] = 1
-
-# We use now Scikit-Learn's linear regressor and ridge regressor
-# OLS part
-clf = skl.LinearRegression().fit(X, Energies)
-ytilde = clf.predict(X)
-EoS['Eols']  = ytilde
-# The mean squared error                               
-print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
-# Explained variance score: 1 is perfect prediction                                 
-print('Variance score: %.2f' % r2_score(Energies, ytilde))
-# Mean absolute error                                                           
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
-print(clf.coef_, clf.intercept_)
-
-# The Ridge regression with a hyperparameter lambda = 0.1
-_lambda = 0.1
-clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
-yridge = clf_ridge.predict(X)
-EoS['Eridge']  = yridge
-# The mean squared error                               
-print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
-# Explained variance score: 1 is perfect prediction                                 
-print('Variance score: %.2f' % r2_score(Energies, yridge))
-# Mean absolute error                                                           
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
-print(clf_ridge.coef_, clf_ridge.intercept_)
-
-fig, ax = plt.subplots()
-ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
-ax.set_ylabel(r'Energy per particle')
-ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,
-            label='Theoretical data')
-ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
-            label='OLS')
-ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
-            label='Ridge $\lambda = 0.1$')
-ax.legend()
-save_fig("EoSfitting")
-plt.show()
-
-

-The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. Can you give an interpretation of the various powers of \( \rho \)? - -

-We note also that there is a small deviation between the -standard OLS and the Ridge regression at higher densities. We discuss this in more detail -below. - -

-









- -

Splitting our Data in Training and Test data

- -

-It is normal in essentially all Machine Learning studies to split the -data in a training set and a test set (sometimes also an additional -validation set). Scikit-Learn has an own function for this. There -is no explicit recipe for how much data should be included as training -data and say test data. An accepted rule of thumb is to use -approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will -postpone a discussion of this splitting to the end of these notes and -our discussion of the so-called bias-variance tradeoff. Here we -limit ourselves to repeat the above equation of state fitting example -but now splitting the data into a training set and a test set. - -

- - -

import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from sklearn.model_selection import train_test_split
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-def R2(y_data, y_model):
-    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
-def MSE(y_data,y_model):
-    n = np.size(y_model)
-    return np.sum((y_data-y_model)**2)/n
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as  csv file and organized into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-#  The design matrix now as function of various polytrops
-X = np.zeros((len(Density),5))
-X[:,0] = 1
-X[:,1] = Density**(2.0/3.0)
-X[:,2] = Density
-X[:,3] = Density**(4.0/3.0)
-X[:,4] = Density**(5.0/3.0)
-# We split the data in test and training data
-X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
-# matrix inversion to find beta
-beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
-# and then make the prediction
-ytilde = X_train @ beta
-print("Training R2")
-print(R2(y_train,ytilde))
-print("Training MSE")
-print(MSE(y_train,ytilde))
-ypredict = X_test @ beta
-print("Test R2")
-print(R2(y_test,ypredict))
-print("Test MSE")
-print(MSE(y_test,ypredict))
-
-

-









- -

The singular value decomposition

- -

-

- -

- -

-The examples we have looked at so far are cases where we normally can -invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we -did both for the masses and the fitting of the equation of state, -leads to row vectors of the design matrix which are essentially -orthogonal due to the polynomial character of our model. This may -however not the be case in general and a standard matrix inversion -algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit -the coupling constant of the widely used Ising model. -There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. - -

-This is given by the Singular Value Decomposition algorithm, perhaps -the most powerful linear algebra algorithm. Let us look at a -different example where we may have problems with the standard matrix -inversion algorithm. Thereafter we dive into the math of the SVD. - - -

- - -

-









- -

The Ising model

- -

-The one-dimensional Ising model with nearest neighbor interaction, no -external field and a constant coupling constant \( J \) is given by - -$$ -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\label{_auto1} -\end{align} -$$ - -

-where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins -in the system is determined by \( L \). For the one-dimensional system -there is no phase transition. - -

-We will look at a system of \( L = 40 \) spins with a coupling constant of -\( J = 1 \). To get enough training data we will generate 10000 states -with their respective energies. - -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from mpl_toolkits.axes_grid1 import make_axes_locatable
-import seaborn as sns
-import scipy.linalg as scl
-from sklearn.model_selection import train_test_split
-import tqdm
-sns.set(color_codes=True)
-cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
-
-L = 40
-n = int(1e4)
-
-spins = np.random.choice([-1, 1], size=(n, L))
-J = 1.0
-
-energies = np.zeros(n)
-
-for i in range(n):
-    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-
-

-Here we use ordinary least squares -regression to predict the energy for the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use linear regression to fit a value for -the coupling constant to achieve this. - -

-









- -

Reformulating the problem to suit regression

- -

-A more general form for the one-dimensional Ising model is - -$$ -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\label{_auto2} -\end{align} -$$ - -

-Here we allow for interactions beyond the nearest neighbors and a state dependent -coupling constant. This latter expression can be formulated as -a matrix-product -$$ -\begin{align} - \boldsymbol{H} = \boldsymbol{X} J, -\label{_auto3} -\end{align} -$$ - -

-where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the -elements \( -J_{jk} \). This form of writing the energy fits perfectly -with the form utilized in linear regression, that is - -$$ -\begin{align} - \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}, -\label{_auto4} -\end{align} -$$ - -

-We split the data in training and test data as discussed in the previous example - -

- - -

X = np.zeros((n, L ** 2))
-for i in range(n):
-    X[i] = np.outer(spins[i], spins[i]).ravel()
-y = energies
-X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
-
-

-









- -

Linear regression

- -

-In the ordinary least squares method we choose the cost function - -$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}. -\label{_auto5} -\end{align} -$$ - -

-We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above. -This yields the expression for \( \boldsymbol{\beta} \) to be - -$$ - \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}}, -$$ - -

-which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist -an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an -intercept, i.e., a constant term, we must make sure that the -first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here - -

- - -

X_train_own = np.concatenate(
-    (np.ones(len(X_train))[:, np.newaxis], X_train),
-    axis=1
-)
-X_test_own = np.concatenate(
-    (np.ones(len(X_test))[:, np.newaxis], X_test),
-    axis=1
-)
-
-

- - -

def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
-    return scl.inv(x.T @ x) @ (x.T @ y)
-beta = ols_inv(X_train_own, y_train)
-
-

-









- -

Singular Value decomposition

- -

-Doing the inversion directly turns out to be a bad idea since the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular -value decomposition. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as - -$$ - \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y}, -$$ - -

-where the pseudoinverse of \( \boldsymbol{X} \) is given by - -$$ - \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}. -$$ - -

-Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \), -where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below). -where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for -\( \omega \) to -$$ -\begin{align} - \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}. -\label{_auto6} -\end{align} -$$ - -

-Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a -general matrix. Instead, doing \( QR \)-factorization and solving the -linear system as an equation would reduce this down to -\( \mathcal{O}(n^2) \) operations. - -

- - -

def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
-    u, s, v = scl.svd(x)
-    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
-
-

- - -

beta = ols_svd(X_train_own,y_train)
-
-

-When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here - -

- - -

J = beta[1:].reshape(L, L)
-
-

-A way of looking at the coefficients in \( J \) is to plot the matrices as images. - -

- - -

fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J, **cmap_args)
-plt.title("OLS", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-plt.show()
-
-

-It is interesting to note that OLS -considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as -valid matrix elements for \( J \). -In our discussion below on hyperparameters and Ridge and Lasso regression we will see that -this problem can be removed, partly and only with Lasso regression. - -

-In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? - -

-









- -

Linear Regression Problems

- -

-One of the typical problems we encounter with linear regression, in particular -when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \) -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix -$$ -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} -$$ - -

-The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. - -

-Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{x} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -$$ -\begin{align*} -\boldsymbol{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -$$ - -We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. -This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero. - -

-









- -

Fixing the singularity

- -

-If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem -$$ -\begin{align} -\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, -\label{_auto7} -\end{align} -$$ - -has linearly dependent column vectors, we will not be able to compute the inverse -of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \). -The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits. -This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters \( \beta_i \) cannot be estimated. - -

-A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change -$$ -\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, -$$ - -where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later. - -

-









- -

Basic math of the SVD

- -

-From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is -a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \) -we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \). -The matrix has then a set of eigenpairs - -$$ -(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), -$$ - -and the eigenvalues are given by the diagonal matrix -$$ -\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). -$$ - -The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) -$$ -\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ - -with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \). - -

-Not all square matrices are diagonalizable. A matrix like the one discussed above -$$ -\boldsymbol{X} = \begin{bmatrix} -1& -1 \\ -1& -1\\ -\end{bmatrix} -$$ - -is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition -\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled. - -

-









- -

The SVD, a Fantastic Algorithm

- -

-However, and this is the strength of the SVD algorithm, any general -matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and -two orthogonal/unitary matrices. The Singular Value Decompostion -(SVD) theorem -states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in -terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( n\times n \) -and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has -dimensionality \( m \times m \) and the last dimensionality \( n\times n \). -We have then - -$$ -\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T -$$ - -

-As an example, the above defective matrix can be decomposed as - -$$ -\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ - -

-with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). -The SVD exits always! - -

-









- -

Another Example

- -

-Consider the following matrix which can be SVD decomposed as - -$$ -\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. -$$ - -

-This is a \( 3\times 2 \) matrix which is decomposed in terms of a -\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see -that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?). - -

-And the SVD -decomposition (singular values) gives eigenvalues -\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), the -eigenvalues (singular values) are zero. - -

-In the general case, where our design matrix \( \boldsymbol{X} \) has dimension -\( n\times p \), the matrix is thus decomposed into an \( n\times n \) -orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) -and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) -singular values \( \sigma_i\lg 0 \) on the main diagonal and zeros filling -the rest of the matrix. There are at most \( p \) singular values -assuming that \( n > p \). In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have \( p > n \). These are often cases that lead to -near singular or singular matrices. - -

-The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors. - -

-









- -

Economy-size SVD

- -

-If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n -\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however -irrelevant in our calculations since they are multiplied with the -zeros in \( \boldsymbol{\Sigma} \). - -

-The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns -in either \( \boldsymbol{U} \) or \( \boldsymbol{V} \) that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. - -

-If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). -If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). -The \( n=p \) case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. - -

-









- -

Mathematical Properties

- -

-There are several interesting mathematical properties which will be -relevant when we are going to discuss the differences between say -ordinary least squares (OLS) and Ridge regression. - -

-We have from OLS that the parameters of the linear approximation are given by -$$ -\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ - -

-The matrix to invert can be rewritten in terms of our SVD decomposition as - -$$ -\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. -$$ - -Using the orthogonality properties of \( \boldsymbol{U} \) we have - -$$ -\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T, -$$ - -with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared. - -

-This means that -$$ -(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D}, -$$ - -that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that -$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}, -$$ - -that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same. - -

-Going back to our OLS equation we have -$$ -\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. -$$ - -We will come back to this expression when we discuss Ridge regression. - -

-









- -

Ridge and LASSO Regression

- -

-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}\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 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}. -$$ - -

-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 - -$$ -{\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. -$$ - -

-









- -

More on Ridge Regression

- -

-Using the matrix-vector expression for Ridge regression, - -$$ -C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta}, -$$ - -

-by 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 - -$$ -\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. - -

-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 -are rather interesting. - -

-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had -$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}. -$$ - -

-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as -$$ -\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} -$$ - -

-For Ridge regression this becomes - -$$ -\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\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} \). - -

-









- -

Interpreting the Ridge results

- -

-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} \). - -

-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. -Actually, calculating the variance of \( \boldsymbol{X}\boldsymbol{v}_j \) shows that this quantity is equal to \( \sigma_j^2/n \). -With a parameter \( \lambda \) we can thus shrink the role of specific parameters. - -

-









- -

More interpretations

- -

-For the sake of simplicity, let us assume that the design matrix is orthonormal, that is - -$$ -\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. -$$ - -

-In this case the standard OLS results in -$$ -\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^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. - -

-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. - -

-









- -

Where are we going?

- -

-Before we proceed, we need to rethink what we have been doing. In our -eager to fit the data, we have omitted several important elements in -our regression analysis. In what follows we will - -

    -
  1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
  2. -
  3. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
  4. -
- -This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. - -

-









- -

Resampling methods

-
- -

-Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. -

- - -

-









- -

Resampling approaches can be computationally expensive

-
- -

- -

-Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. - - -

- - -

-









- -

Why resampling methods ?

-
-Statistical analysis. -

- -

-
- - -

-









- -

Statistical analysis

-
- -

- -

-
- - -

-









- -

Statistics

-
- -

-The probability distribution function (PDF) is a function -\( p(x) \) on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of \( X \) occur: -$$ -p(x) = \mathrm{prob}(X=x) -$$ - -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around \( x \) to be \( p(x)dx \). The continuous function \( p(x) \) then gives us -the density of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval \( [a,\,b] \) is then just the integral: -$$ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx -$$ - -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. -

- - -

-









- -

Statistics, moments

-
- -

-A particularly useful class of special expectation values are the -moments. The \( n \)-th moment of the PDF \( p \) is defined as -follows: -$$ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx -$$ - -The zero-th moment \( \langle 1\rangle \) is just the normalization condition of -\( p \). The first moment, \( \langle x\rangle \), is called the mean of \( p \) -and often denoted by the letter \( \mu \): -$$ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx -$$ -

- - -

-









- -

Statistics, central moments

-
- -

-A special version of the moments is the set of central moments, -the n-th central moment defined as: -$$ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -$$ - -The zero-th and first central moments are both trivial, equal \( 1 \) and -\( 0 \), respectively. But the second central moment, known as the -variance of \( p \), is of particular interest. For the stochastic -variable \( X \), the variance is denoted as \( \sigma^2_X \) or \( \mathrm{var}(X) \): -$$ -\begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx -\label{_auto8}\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx -\label{_auto9}\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 -\label{_auto10}\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\label{_auto11} -\end{align} -$$ - -The square root of the variance, \( \sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle} \) is called the standard deviation of \( p \). It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the spread of \( p \) around its mean. -

- - -

-









- -

Statistics, covariance

-
- -

-Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set \( \{X_i\} \) of \( n \) -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF \( P(x_1,\dots,x_n) \). The covariance of two -of the stochastic variables, \( X_i \) and \( X_j \), is defined as follows: -$$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\label{eq:def_covariance} -\end{align} -$$ - -with -$$ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -$$ -

- - -

-









- -

Statistics, more covariance

-
- -

-If we consider the above covariance as a matrix \( C_{ij}=\mathrm{cov}(X_i,\,X_j) \), then the diagonal elements are just the familiar -variances, \( C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i) \). It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables \( X_i \) and -\( X_j \), (\( i\neq j \)): -$$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\label{_auto12}\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle -\label{_auto13}\\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle -\label{_auto14}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle -\label{_auto15}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\label{_auto16} -\end{align} -$$ -

- - -

-









- -

Statistics, independent variables

-
- -

-If \( X_i \) and \( X_j \) are independent, we get -\( \langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle \), resulting in \( \mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j) \). - -

-Also useful for us is the covariance of linear combinations of -stochastic variables. Let \( \{X_i\} \) and \( \{Y_i\} \) be two sets of -stochastic variables. Let also \( \{a_i\} \) and \( \{b_i\} \) be two sets of -scalars. Consider the linear combination: -$$ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j -$$ - -By the linearity of the expectation value -$$ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) -$$ -

- - -

-









- -

Statistics, more variance

-
- -

-Now, since the variance is just \( \mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i) \), we get -the variance of the linear combination \( U = \sum_i a_i X_i \): -$$ -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\label{eq:variance_linear_combination} -\end{equation} -$$ - -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -$$ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -$$ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -which will become very useful in our study of the error in the mean -value of a set of measurements. -

- - -

-









- -

Statistics and stochastic processes

-
- -

-A stochastic process is a process that produces sequentially a -chain of values: -$$ -\{x_1, x_2,\dots\,x_k,\dots\}. -$$ - -We will call these -values our measurements and the entire set as our measured -sample. The action of measuring all the elements of a sample -we will call a stochastic experiment since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF \( p_X^{\phantom X}(x) \), where \( X \) is just the formal symbol for the -stochastic variable whose PDF is \( p_X^{\phantom X}(x) \). Instead of -trying to determine the full distribution \( p \) we are often only -interested in finding the few lowest moments, like the mean -\( \mu_X^{\phantom X} \) and the variance \( \sigma_X^{\phantom X} \). -

- - -

- - -

Statistics and sample variables

-
- -

-In practical situations a sample is always of finite size. Let that -size be \( n \). The expectation value of a sample, the sample mean, is then defined as follows: -$$ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -$$ - -The sample variance is: -$$ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -$$ - -its square root being the standard deviation of the sample. The -sample covariance is: -$$ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -$$ -

- - -

-









- -

Statistics, sample variance and covariance

-
- -

-Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq. \eqref{eq:def_covariance} is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. - -

-These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean \( \mu_X \), variance \( \mathrm{var}(X) \) -and covariance \( \mathrm{cov}(X,Y) \). -

- - -

-









- -

Statistics, law of large numbers

-
- -

-The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean \( \mu_X^{\phantom X} \) of the chosen PDF: -$$ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} -$$ - -The sample mean \( \bar{x}_n \) works therefore as an estimate of the true -mean \( \mu_X^{\phantom X} \). - -

-What we need to find out is how good an approximation \( \bar{x}_n \) is to -\( \mu_X^{\phantom X} \). In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the error of the sample mean, or -just sample error, and denote it by \( \mathrm{err}_X^{\phantom X} \). In -practice, we will only be able to produce an estimate of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. -

- - -

-









- -

Statistics, more on sample error

-
- -

-Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements \( x_i \) -can be associated with its own stochastic variable \( X_i \). The -stochastic variable \( \overline X_n \) for the sample mean \( \bar{x}_n \) is -then just a linear combination, already familiar to us: -$$ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i -$$ - -All the coefficients are just equal \( 1/n \). The PDF of \( \overline X_n \), -denoted by \( p_{\overline X_n}(x) \) is the desired PDF of the sample -means. -

- - -

-









- -

Statistics

-
- -

-The probability density of obtaining a sample mean \( \bar x_n \) -is the product of probabilities of obtaining arbitrary values \( x_1, -x_2,\dots,x_n \) with the constraint that the mean of the set \( \{x_i\} \) -is \( \bar x_n \): -$$ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 -$$ - -And in particular we are interested in its variance \( \mathrm{var}(\overline X_n) \). -

- - -

-









- -

Statistics, central limit theorem

-
- -

-It is generally not possible to express \( p_{\overline X_n}(x) \) in a -closed form given an arbitrary PDF \( p_X^{\phantom X} \) and a number -\( n \). But for the limit \( n\to\infty \) it is possible to make an -approximation. The very important result is called the central limit theorem. It tells us that as \( n \) goes to infinity, -\( p_{\overline X_n}(x) \) approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, \( \mu_{X}^{\phantom X} \) -and \( \sigma_{X}^{2} \), respectively: -$$ -\begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\label{eq:central_limit_gaussian} -\end{equation} -$$ -

- - -

-









- -

Statistics, more technicalities

-
- -

-The desired variance -\( \mathrm{var}(\overline X_n) \), i.e. the sample error squared -\( \mathrm{err}_X^2 \), is given by: -$$ -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\label{eq:error_exact} -\end{equation} -$$ - -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -\( \mu_{X_i}^{\phantom X} \) of the stochastic variables \( X_i \). To -calculate these requires that we know the true multivariate PDF of all -the \( X_i \). But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the \( X_i \), estimating all properties of -\( X_i \) through the measurements of the sample. -

- - -

-









- -

Statistics

-
- -

-Our estimate of \( \mu_{X_i}^{\phantom X} \) is then the sample mean \( \bar x \) -itself, in accordance with the the central limit theorem: -$$ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x -$$ - -Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an -estimate of the covariance in Eq. \eqref{eq:error_exact} -$$ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, -$$ - -resulting in -$$ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) -$$ -

- - -

-









- -

Statistics and sample variance

-
- -

-By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables \( X_i \) -$$ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, -$$ - -which is approximated as -$$ -\begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\label{eq:var_estimate_i_think} -\end{equation} -$$ - -

-Now we can calculate an estimate of the error -\( \mathrm{err}_X^{\phantom X} \) of the sample mean \( \bar x_n \): -$$ -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\label{eq:error_estimate} -\end{align} -$$ - -which is nothing but the sample covariance divided by the number of -measurements in the sample. -

- - -

-









- -

Statistics, uncorrelated results

-
- -

- -

-In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables \( X_i \) are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: -$$ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), -$$ - -resulting in -$$ -\begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\label{eq:error_estimate_uncorrel} -\end{equation} -$$ - -where in the second step we have used Eq. \eqref{eq:var_estimate_i_think}. -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. -

- - -

-









- -

Statistics, computations

-
- -

-For computational purposes one usually splits up the estimate of -\( \mathrm{err}_X^2 \), given by Eq. \eqref{eq:error_estimate}, into two -parts -$$ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), -$$ - -which equals -$$ -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) -\label{eq:error_estimate_split_up} -\end{equation} -$$ - -The first term is the same as the error in the uncorrelated case, -Eq. \eqref{eq:error_estimate_uncorrel}. This means that the second -term accounts for the error correction due to correlation between the -measurements. For uncorrelated measurements this second term is zero. -

- - -

-









- -

Statistics, more on computations of errors

-
- -

-Computationally the uncorrelated first term is much easier to treat -efficiently than the second. -$$ -\mathrm{var}(x) = \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)^2 = -\left(\frac{1}{n}\sum_{k=1}^n x_k^2\right) - \bar x_n^2 -$$ - -We just accumulate separately the values \( x^2 \) and \( x \) for every -measurement \( x \) we receive. The correlation term, though, has to be -calculated at the end of the experiment since we need all the -measurements to calculate the cross terms. Therefore, all measurements -have to be stored throughout the experiment. -

- - -

-









- -

Statistics, wrapping up 1

-
- -

-Let us analyze the problem by splitting up the correlation term into -partial sums of the form: -$$ -f_d = \frac{1}{n-d}\sum_{k=1}^{n-d}(x_k - \bar x_n)(x_{k+d} - \bar x_n) -$$ - -The correlation term of the error can now be rewritten in terms of -\( f_d \) -$$ -\frac{2}{n}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) = -2\sum_{d=1}^{n-1} f_d -$$ - -The value of \( f_d \) reflects the correlation between measurements -separated by the distance \( d \) in the sample samples. Notice that for -\( d=0 \), \( f \) is just the sample variance, \( \mathrm{var}(x) \). If we divide \( f_d \) -by \( \mathrm{var}(x) \), we arrive at the so called autocorrelation function -$$ -\kappa_d = \frac{f_d}{\mathrm{var}(x)} -$$ - -which gives us a useful measure of pairwise correlations -starting always at \( 1 \) for \( d=0 \). -

- - -

-









- -

Statistics, final expression

-
- -

-The sample error (see eq. \eqref{eq:error_estimate_split_up}) can now be -written in terms of the autocorrelation function: -$$ -\begin{align} -\mathrm{err}_X^2 &= -\frac{1}{n}\mathrm{var}(x)+\frac{2}{n}\cdot\mathrm{var}(x)\sum_{d=1}^{n-1} -\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=& -\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\ -&=\frac{\tau}{n}\cdot\mathrm{var}(x) -\label{eq:error_estimate_corr_time} -\end{align} -$$ - -and we see that \( \mathrm{err}_X \) can be expressed in terms the -uncorrelated sample variance times a correction factor \( \tau \) which -accounts for the correlation between measurements. We call this -correction factor the autocorrelation time: -$$ -\begin{equation} -\tau = 1+2\sum_{d=1}^{n-1}\kappa_d -\label{eq:autocorrelation_time} -\end{equation} -$$ -

- - -

-









- -

Statistics, effective number of correlations

-
- -

-For a correlation free experiment, \( \tau \) -equals 1. From the point of view of -eq. \eqref{eq:error_estimate_corr_time} we can interpret a sequential -correlation as an effective reduction of the number of measurements by -a factor \( \tau \). The effective number of measurements becomes: -$$ -n_\mathrm{eff} = \frac{n}{\tau} -$$ - -To neglect the autocorrelation time \( \tau \) will always cause our -simple uncorrelated estimate of \( \mathrm{err}_X^2\approx \mathrm{var}(x)/n \) to -be less than the true sample error. The estimate of the error will be -too good. On the other hand, the calculation of the full -autocorrelation time poses an efficiency problem if the set of -measurements is very large. -

- - -

- - -

Linking the regression analysis with a statistical interpretation

- -

-Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. -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. - -

-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 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 \). - -

-









- -

Assumptions made

- -

-The assumption we have made here can be summarized as (and this is going to 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 describes our data -$$ -\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}. -$$ - -

-









- -

Expectation value and variance

- -

-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 -$$ -\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). - -

-









- -

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

- -

-With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value -$$ -\mathbb{E}(\boldsymbol{\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}. -$$ - -This means that the estimator of the regression parameters is unbiased. - -

-We can also calculate the variance - -

-The variance of \( \boldsymbol{\beta} \) is -$$ -\begin{eqnarray*} -\mbox{Var}(\boldsymbol{\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: -\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{ -[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to -construct a confidence interval for the estimates. - -

-In a similar way, we cna obtain analytical expressions for say the -expectation values of the parameters \( \boldsymbol{\beta} \) and their variance -when we employ Ridge regression, and thereby 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 - -$$ -\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. - -

- - -

Cross-validation

- -

-Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e. the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. - -

-The setting of original and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the -training set, plays the role of original data on which the model is -built. The second of these data sets, called the test set, plays the -role of the novel data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of \( \lambda \) using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. - -

-









- -

Computationally expensive

- -

-The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: - -

- - - -

Various steps in cross-validation

- -

-When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this \( k \)-fold cross-validation structures the data splitting. The -samples are divided into \( k \) more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the \( k \) subsets -involves a degree of randomness. This may be fully excluded when -choosing \( k=n \). This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -

- - -

How to set up the cross-validation for Ridge and/or Lasso

- - - -$$ -\begin{align*} -\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} -\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} -\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} -\end{align*} -$$ - - - - -$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ - - - - -









- -

Resampling methods: Jackknife and Bootstrap

- -

-Two famous -resampling methods are the independent bootstrap and the jackknife. - -

-The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as the dependent bootstrap. - -

-The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of \( \overline{X} \) (which often is the case), then there is no -need for bootstrapping. - -

-









- -

Resampling methods: Jackknife

- -

-The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \boldsymbol{x}_i \) denote the vector -$$ -\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ - -

-which equals the vector \( \boldsymbol{x} \) with the exception that observation -number \( i \) is left out. Using this notation, define -\( \widehat{\theta}_i \) to be the estimator -\( \widehat{\theta} \) computed using \( \vec{X}_i \). - -

-









- -

Jackknife code example

-

- - -

from numpy import *
-from numpy.random import randint, randn
-from time import time
-
-def jackknife(data, stat):
-    n = len(data);t = zeros(n); inds = arange(n); t0 = time()
-    ## 'jackknifing' by leaving out an observation for each i                                                                                                                      
-    for i in range(n):
-        t[i] = stat(delete(data,i) )
-
-    # analysis                                                                                                                                                                     
-    print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
-    print("original           bias      std. error")
-    print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
-
-    return t
-
-
-# Returns mean of data samples                                                                                                                                                     
-def stat(data):
-    return mean(data)
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# jackknife returns the data sample                                                                                                                                                
-t = jackknife(x, stat)
-
-

-









- -

Resampling methods: Bootstrap

-
- -

-Bootstrapping is a nonparametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: - -

    -
  1. The bootstrap is quite general, although there are some cases in which it fails.
  2. -
  3. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
  4. -
  5. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
  6. -
  7. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
  8. -
-
- - -

-









- -

Resampling methods: Bootstrap background

- -

-Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, -\( \widehat{\theta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to -estimate \( p(\boldsymbol{t}) \) by the relative frequency of -\( \widehat{\theta} \). You can think of this as using a histogram -in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely -resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point -estimators. - -

-









- -

Resampling methods: More Bootstrap background

- -

-In the case that \( \widehat{\theta} \) has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of \( X_i \), \( p(x) \), had been known, then it would have -been straight forward to do this by: - -

    -
  1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
  2. -
  3. Then using these numbers, we could compute a replica of \( \widehat{\theta} \) called \( \widehat{\theta}^* \).
  4. -
- -By repeated use of (1) and (2), many -estimates of \( \widehat{\theta} \) could have been obtained. The -idea is to use the relative frequency of \( \widehat{\theta}^* \) -(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). - -

-









- -

Resampling methods: Bootstrap approach

- -

-But -unless there is enough information available about the process that -generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general -unknown. Therefore, Efron in 1979 asked the -question: What if we replace \( p(x) \) by the relative frequency -of the observation \( X_i \); if we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - -

-Instead of generating the histogram for the relative -frequency of the observation \( X_i \), just draw the values -\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector -\( \boldsymbol{X} \). - -

-









- -

Resampling methods: Bootstrap steps

- -

-The independent bootstrap works like this: - -

    -
  1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
  2. -
  3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
  4. -
  5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
  6. -
  7. Repeat this process \( k \) times.
  8. -
- -When you are done, you can draw a histogram of the relative frequency -of \( \widehat \theta^* \). This is your estimate of the probability -distribution \( p(t) \). Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of \( \widehat{\theta}^* \). Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of \( \widehat -\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values -\( \widehat \theta ^* \). - -

-









- -

Code example for the Bootstrap method

- -

-The following code starts with a Gaussian distribution with mean value -\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data -used in the bootstrap analysis. The bootstrap analysis returns a data -set after a given number of bootstrap operations (as many as we have -data points). This data set consists of estimated mean values for each -bootstrap operation. The histogram generated by the bootstrap method -shows that the distribution for these mean values is also a Gaussian, -centered around the mean value \( \mu=100 \) but with standard deviation -\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in -this case the same as the number of original data points). The value -of the standard deviation is what we expect from the central limit -theorem. - -

- - -

from numpy import *
-from numpy.random import randint, randn
-from time import time
-import matplotlib.mlab as mlab
-import matplotlib.pyplot as plt
-
-# Returns mean of bootstrap samples                                                                                                                                                
-def stat(data):
-    return mean(data)
-
-# Bootstrap algorithm
-def bootstrap(data, statistic, R):
-    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
-    # non-parametric bootstrap         
-    for i in range(R):
-        t[i] = statistic(data[randint(0,n,n)])
-
-    # analysis    
-    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
-    print("original           bias      std. error")
-    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
-    return t
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# bootstrap returns the data sample                                    
-t = bootstrap(x, stat, datapoints)
-# the histogram of the bootstrapped  data                                                                                                    
-n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
-
-# add a 'best fit' line  
-y = mlab.normpdf( binsboot, mean(t), std(t))
-lt = plt.plot(binsboot, y, 'r--', linewidth=1)
-plt.xlabel('Smarts')
-plt.ylabel('Probability')
-plt.axis([99.5, 100.6, 0, 3.0])
-plt.grid(True)
-
-plt.show()
-
-

-









- -

Code Example for Cross-validation and \( k \)-fold Cross-validation

- -

-The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.model_selection import KFold
-from sklearn.linear_model import Ridge
-from sklearn.model_selection import cross_val_score
-from sklearn.preprocessing import PolynomialFeatures
-
-# A seed just to ensure that the random numbers are the same for every run.
-# Useful for eventual debugging.
-np.random.seed(3155)
-
-# Generate the data.
-nsamples = 100
-x = np.random.randn(nsamples)
-y = 3*x**2 + np.random.randn(nsamples)
-
-## Cross-validation on Ridge regression using KFold only
-
-# Decide degree on polynomial to fit
-poly = PolynomialFeatures(degree = 6)
-
-# Decide which values of lambda to use
-nlambdas = 500
-lambdas = np.logspace(-3, 5, nlambdas)
-
-# Initialize a KFold instance
-k = 5
-kfold = KFold(n_splits = k)
-
-# Perform the cross-validation to estimate MSE
-scores_KFold = np.zeros((nlambdas, k))
-
-i = 0
-for lmb in lambdas:
-    ridge = Ridge(alpha = lmb)
-    j = 0
-    for train_inds, test_inds in kfold.split(x):
-        xtrain = x[train_inds]
-        ytrain = y[train_inds]
-
-        xtest = x[test_inds]
-        ytest = y[test_inds]
-
-        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
-        ridge.fit(Xtrain, ytrain[:, np.newaxis])
-
-        Xtest = poly.fit_transform(xtest[:, np.newaxis])
-        ypred = ridge.predict(Xtest)
-
-        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
-
-        j += 1
-    i += 1
-
-
-estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
-
-## Cross-validation using cross_val_score from sklearn along with KFold
-
-# kfold is an instance initialized above as:
-# kfold = KFold(n_splits = k)
-
-estimated_mse_sklearn = np.zeros(nlambdas)
-i = 0
-for lmb in lambdas:
-    ridge = Ridge(alpha = lmb)
-
-    X = poly.fit_transform(x[:, np.newaxis])
-    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
-
-    # cross_val_score return an array containing the estimated negative mse for every fold.
-    # we have to the the mean of every array in order to get an estimate of the mse of the model
-    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
-
-    i += 1
-
-## Plot and compare the slightly different ways to perform cross-validation
-
-plt.figure()
-
-plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
-plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
-
-plt.xlabel('log10(lambda)')
-plt.ylabel('mse')
-
-plt.legend()
-
-plt.show()
-
-

-









- -

The bias-variance tradeoff

- -

-We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset \( \mathcal{L} \) consisting of the data -\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). - -

-Let us assume that the true data is generated from a noisy model - -$$ -\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} -$$ - -

-where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). - -

-In our derivation of the ordinary least squares method we defined then -an approximation to the function \( f \) in terms of the parameters -\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, -that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). - -

-Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function -$$ -C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. -$$ - -

-We can rewrite this as -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2. -$$ - -

-The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error \( \boldsymbol{\epsilon} \). - -

-To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). -We use a more compact notation in terms of the expectation value -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], -$$ - -and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], -$$ - -which, using the abovementioned expectation values can be rewritten as -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, -$$ - -that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \). - -

-









- -

Example code for Bias-Variance tradeoff

-

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-
-np.random.seed(2018)
-
-n = 500
-n_boostraps = 100
-degree = 18  # A quite high value, just to show.
-noise = 0.1
-
-# Make data set.
-x = np.linspace(-1, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
-
-# Hold out some test data that is never used in training.
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-# Combine x transformation and model into one operation.
-# Not neccesary, but convenient.
-model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
-
-# The following (m x n_bootstraps) matrix holds the column vectors y_pred
-# for each bootstrap iteration.
-y_pred = np.empty((y_test.shape[0], n_boostraps))
-for i in range(n_boostraps):
-    x_, y_ = resample(x_train, y_train)
-
-    # Evaluate the new model on the same test data each time.
-    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
-# Note: Expectations and variances taken w.r.t. different training
-# data sets, hence the axis=1. Subsequent means are taken across the test data
-# set in order to obtain a total value, but before this we have error/bias/variance
-# calculated per data point in the test set.
-# Note 2: The use of keepdims=True is important in the calculation of bias as this 
-# maintains the column vector form. Dropping this yields very unexpected results.
-error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
-bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
-variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
-print('Error:', error)
-print('Bias^2:', bias)
-print('Var:', variance)
-print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
-
-plt.plot(x[::5, :], y[::5, :], label='f(x)')
-plt.scatter(x_test, y_test, label='Data points')
-plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
-plt.legend()
-plt.show()
-
-

-









- -

Understanding what happens

-

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-
-np.random.seed(2018)
-
-n = 40
-n_boostraps = 100
-maxdegree = 14
-
-
-# Make data set.
-x = np.linspace(-3, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
-error = np.zeros(maxdegree)
-bias = np.zeros(maxdegree)
-variance = np.zeros(maxdegree)
-polydegree = np.zeros(maxdegree)
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-for degree in range(maxdegree):
-    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
-    y_pred = np.empty((y_test.shape[0], n_boostraps))
-    for i in range(n_boostraps):
-        x_, y_ = resample(x_train, y_train)
-        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
-    polydegree[degree] = degree
-    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
-    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
-    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
-    print('Polynomial degree:', degree)
-    print('Error:', error[degree])
-    print('Bias^2:', bias[degree])
-    print('Var:', variance[degree])
-    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-
-plt.plot(polydegree, np.log10(error), label='Error')
-plt.plot(polydegree, bias, label='bias')
-plt.plot(polydegree, variance, label='Variance')
-plt.legend()
-plt.show()
-
-

- - -

Summing up

- -

-The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - -

-The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below \( Var(\epsilon) \), the irreducible error. - -

-What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - -

-









- -

Another Example rom Scikit-Learn's Repository

-

- - -

"""
-============================
-Underfitting vs. Overfitting
-============================
-
-This example demonstrates the problems of underfitting and overfitting and
-how we can use linear regression with polynomial features to approximate
-nonlinear functions. The plot shows the function that we want to approximate,
-which is a part of the cosine function. In addition, the samples from the
-real function and the approximations of different models are displayed. The
-models have polynomial features of different degrees. We can see that a
-linear function (polynomial with degree 1) is not sufficient to fit the
-training samples. This is called **underfitting**. A polynomial of degree 4
-approximates the true function almost perfectly. However, for higher degrees
-the model will **overfit** the training data, i.e. it learns the noise of the
-training data.
-We evaluate quantitatively **overfitting** / **underfitting** by using
-cross-validation. We calculate the mean squared error (MSE) on the validation
-set, the higher, the less likely the model generalizes correctly from the
-training data.
-"""
-
-print(__doc__)
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.pipeline import Pipeline
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.linear_model import LinearRegression
-from sklearn.model_selection import cross_val_score
-
-
-def true_fun(X):
-    return np.cos(1.5 * np.pi * X)
-
-np.random.seed(0)
-
-n_samples = 30
-degrees = [1, 4, 15]
-
-X = np.sort(np.random.rand(n_samples))
-y = true_fun(X) + np.random.randn(n_samples) * 0.1
-
-plt.figure(figsize=(14, 5))
-for i in range(len(degrees)):
-    ax = plt.subplot(1, len(degrees), i + 1)
-    plt.setp(ax, xticks=(), yticks=())
-
-    polynomial_features = PolynomialFeatures(degree=degrees[i],
-                                             include_bias=False)
-    linear_regression = LinearRegression()
-    pipeline = Pipeline([("polynomial_features", polynomial_features),
-                         ("linear_regression", linear_regression)])
-    pipeline.fit(X[:, np.newaxis], y)
-
-    # Evaluate the models using crossvalidation
-    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
-                             scoring="neg_mean_squared_error", cv=10)
-
-    X_test = np.linspace(0, 1, 100)
-    plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
-    plt.plot(X_test, true_fun(X_test), label="True function")
-    plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
-    plt.xlabel("x")
-    plt.ylabel("y")
-    plt.xlim((0, 1))
-    plt.ylim((-2, 2))
-    plt.legend(loc="best")
-    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
-        degrees[i], -scores.mean(), scores.std()))
-plt.show()
-
-

-









- -

The one-dimensional Ising model

- -

-Let us bring back the Ising model again, but now with an additional -focus on Ridge and Lasso regression as well. We repeat some of the -basic parts of the Ising model and the setup of the training and test -data. The one-dimensional Ising model with nearest neighbor -interaction, no external field and a constant coupling constant \( J \) is -given by - -$$ -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\label{_auto17} -\end{align} -$$ - -where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins in the system is determined by \( L \). For the one-dimensional system there is no phase transition. - -

-We will look at a system of \( L = 40 \) spins with a coupling constant of \( J = 1 \). To get enough training data we will generate 10000 states with their respective energies. - -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from mpl_toolkits.axes_grid1 import make_axes_locatable
-import seaborn as sns
-import scipy.linalg as scl
-from sklearn.model_selection import train_test_split
-import sklearn.linear_model as skl
-import tqdm
-sns.set(color_codes=True)
-cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
-
-L = 40
-n = int(1e4)
-
-spins = np.random.choice([-1, 1], size=(n, L))
-J = 1.0
-
-energies = np.zeros(n)
-
-for i in range(n):
-    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-
-

-A more general form for the one-dimensional Ising model is - -$$ -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\label{_auto18} -\end{align} -$$ - -

-Here we allow for interactions beyond the nearest neighbors and a more -adaptive coupling matrix. This latter expression can be formulated as -a matrix-product on the form -$$ -\begin{align} - H = X J, -\label{_auto19} -\end{align} -$$ - -

-where \( X_{jk} = s_j s_k \) and \( J \) is the matrix consisting of the -elements \( -J_{jk} \). This form of writing the energy fits perfectly -with the form utilized in linear regression, viz. -$$ -\begin{align} - \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}. -\label{_auto20} -\end{align} -$$ - -We organize the data as we did above -

- - -

X = np.zeros((n, L ** 2))
-for i in range(n):
-    X[i] = np.outer(spins[i], spins[i]).ravel()
-y = energies
-X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)
-
-X_train_own = np.concatenate(
-    (np.ones(len(X_train))[:, np.newaxis], X_train),
-    axis=1
-)
-
-X_test_own = np.concatenate(
-    (np.ones(len(X_test))[:, np.newaxis], X_test),
-    axis=1
-)
-
-

-We will do all fitting with Scikit-Learn, - -

- - -

clf = skl.LinearRegression().fit(X_train, y_train)
-
-

-When extracting the \( J \)-matrix we make sure to remove the intercept -

- - -

J_sk = clf.coef_.reshape(L, L)
-
-

-And then we plot the results -

- - -

fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_sk, **cmap_args)
-plt.title("LinearRegression from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-plt.show()
-
-

-The results perfectly with our previous discussion where we used our own code. - -

-









- -

Ridge regression

- -

-Having explored the ordinary least squares we move on to ridge -regression. In ridge regression we include a regularizer. This -involves a new cost function which leads to a new estimate for the -weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The -cost function is given by - -$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}. -\label{_auto21} -\end{align} -$$ - -

- - -

_lambda = 0.1
-clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
-J_ridge_sk = clf_ridge.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_ridge_sk, **cmap_args)
-plt.title("Ridge from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-plt.show()
-
-

-









- -

LASSO regression

- -

-In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function. - -$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}. -\label{_auto22} -\end{align} -$$ - -

-Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn. - -

- - -

clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)
-J_lasso_sk = clf_lasso.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_lasso_sk, **cmap_args)
-plt.title("Lasso from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-plt.show()
-
-

-It is quite striking how LASSO breaks the symmetry of the coupling -constant as opposed to ridge and OLS. We get a sparse solution with -\( J_{j, j + 1} = -1 \). - -

-









- -

Performance as function of the regularization parameter

- -

-We see how the different models perform for a different set of values for \( \lambda \). - -

- - -

lambdas = np.logspace(-4, 5, 10)
-
-train_errors = {
-    "ols_sk": np.zeros(lambdas.size),
-    "ridge_sk": np.zeros(lambdas.size),
-    "lasso_sk": np.zeros(lambdas.size)
-}
-
-test_errors = {
-    "ols_sk": np.zeros(lambdas.size),
-    "ridge_sk": np.zeros(lambdas.size),
-    "lasso_sk": np.zeros(lambdas.size)
-}
-
-plot_counter = 1
-
-fig = plt.figure(figsize=(32, 54))
-
-for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
-    for key, method in zip(
-        ["ols_sk", "ridge_sk", "lasso_sk"],
-        [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
-    ):
-        method = method.fit(X_train, y_train)
-
-        train_errors[key][i] = method.score(X_train, y_train)
-        test_errors[key][i] = method.score(X_test, y_test)
-
-        omega = method.coef_.reshape(L, L)
-
-        plt.subplot(10, 5, plot_counter)
-        plt.imshow(omega, **cmap_args)
-        plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda))
-        plot_counter += 1
-
-plt.show()
-
-

-We see that LASSO reaches a good solution for low -values of \( \lambda \), but will "wither" when we increase \( \lambda \) too -much. Ridge is more stable over a larger range of values for -\( \lambda \), but eventually also fades away. - -

-









- -

Finding the optimal value of \( \lambda \)

- -

-To determine which value of \( \lambda \) is best we plot the accuracy of -the models when predicting the training and the testing set. We expect -the accuracy of the training set to be quite good, but if the accuracy -of the testing set is much lower this tells us that we might be -subject to an overfit model. The ideal scenario is an accuracy on the -testing set that is close to the accuracy of the training set. - -

- - -

fig = plt.figure(figsize=(20, 14))
-
-colors = {
-    "ols_sk": "r",
-    "ridge_sk": "y",
-    "lasso_sk": "c"
-}
-
-for key in train_errors:
-    plt.semilogx(
-        lambdas,
-        train_errors[key],
-        colors[key],
-        label="Train {0}".format(key),
-        linewidth=4.0
-    )
-
-for key in test_errors:
-    plt.semilogx(
-        lambdas,
-        test_errors[key],
-        colors[key] + "--",
-        label="Test {0}".format(key),
-        linewidth=4.0
-    )
-plt.legend(loc="best", fontsize=18)
-plt.xlabel(r"$\lambda$", fontsize=18)
-plt.ylabel(r"$R^2$", fontsize=18)
-plt.tick_params(labelsize=18)
-plt.show()
-
-

-From the above figure we can see that LASSO with \( \lambda = 10^{-2} \) -achieves a very good accuracy on the test set. This by far surpasses the -other models for all values of \( \lambda \). - -

-









- -

Further Exercises

- -

Exercise 1

- -

-We will 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,1)
-y = 5*x*x+0.1*np.random.randn(100,1)
-
-
    -
  1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial.
  2. -
  3. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
  4. -
  5. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  6. -
- -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -

-You can use the functionality included in scikit-learn. If you feel -for it, you can use your own program and define functions which -compute the above two functions. Discuss the meaning of these -results. Try also to vary the coefficient in front of the added -stochastic noise term and discuss the quality of the fits. - -

Exercise 2, variance of the parameters \( \beta \) in linear regression

- -

-Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as - -$$ -\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, -$$ - -with -$$ -\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, -$$ - -where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)). - -

Exercise 3

- -

-This exercise is a continuation of exercise 1. 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. You can use the code under the Regression as an example on how to use the Ridge and the Lasso 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,1)
-y = 5*x*x+0.1*np.random.randn(100,1)
-
-
    -
  1. Write your own code for the Ridge method and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 1. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
  2. -
  3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
  4. -
  5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing 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 that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions
  6. -
  7. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.
  8. -
  9. Try to implement the cross-validation as well.
  10. -
  11. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  12. -
- -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. - -

Exercise 4

- -

-We will study how -to fit polynomials to a specific two-dimensional function called -Franke's -function. This -is a function which has been widely used when testing various interpolation and fitting -algorithms. Furthermore, after having established the model and the -method, we will employ resamling techniques such as the cross-validation and/or -the bootstrap methods, in order to perform a proper assessment of our models. - -

-The Franke function, which is a weighted sum of four exponentials reads as follows -$$ -\begin{align*} -f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ -&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. -\end{align*} -$$ - -

-The function will be defined for \( x,y\in [0,1] \). Our first step will -be to perform an OLS regression analysis of this function, trying out -a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y, -x^2, y^2, xy, \dots] \). We will also include cross-validation and -bootstrap as resampling techniques. As in homeworks 1 and 2, we -can use a uniform distribution to set up the arrays of values for \( x \) -and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size. -In this case we will have two predictors and need to fit a -function (for example a polynomial) of \( x \) and \( y \). Thereafter we will -repeat much of the same procedure using the the Ridge and -Lasso regression methods, introducing thus a dependence on the bias -(penalty) \( \lambda \). - -

-The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) -

- - -

from mpl_toolkits.mplot3d import Axes3D
-import matplotlib.pyplot as plt
-from matplotlib import cm
-from matplotlib.ticker import LinearLocator, FormatStrFormatter
-import numpy as np
-from random import random, seed
-
-fig = plt.figure()
-ax = fig.gca(projection='3d')
-
-# Make data.
-x = np.arange(0, 1, 0.05)
-y = np.arange(0, 1, 0.05)
-x, y = np.meshgrid(x,y)
-
-
-def FrankeFunction(x,y):
-    term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-    term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-    term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-    term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-    return term1 + term2 + term3 + term4
-
-
-z = FrankeFunction(x, y)
-
-# Plot the surface.
-surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
-                       linewidth=0, antialiased=False)
-
-# Customize the z axis.
-ax.set_zlim(-0.10, 1.40)
-ax.zaxis.set_major_locator(LinearLocator(10))
-ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
-
-# Add a color bar which maps values to colors.
-fig.colorbar(surf, shrink=0.5, aspect=5)
-
-plt.show()
-
-

-We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where -\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform -distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition -an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). - -

-Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3 -and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -

-Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm -and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models. - -

-Write then your own code for the Ridge method, either using matrix -inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the -previous exercise (for the same polynomials and include resampling -techniques) but now for different values of \( \lambda \). Compare and -analyze your results with those obtained with standard OLS. Study the -dependence on \( \lambda \) while also varying eventually the strength of -the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). - -

-Then perform the same studies but now with Lasso regression. Use the functionalities of -scikit-learn. Give a critical discussion of the three methods and a -judgement of which model fits the data best. - - - - -

- © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - - - - diff --git a/doc/src/Regression/Regression.aux b/doc/src/Regression/Regression.aux deleted file mode 100644 index 2e3e588c5..000000000 --- a/doc/src/Regression/Regression.aux +++ /dev/null @@ -1,119 +0,0 @@ -\relax -\providecommand\hyper@newdestlabel[2]{} -\providecommand\zref@newlabel[2]{} -\providecommand\HyperFirstAtBeginDocument{\AtBeginDocument} -\HyperFirstAtBeginDocument{\ifx\hyper@anchor\@undefined -\global\let\oldcontentsline\contentsline -\gdef\contentsline#1#2#3#4{\oldcontentsline{#1}{#2}{#3}} -\global\let\oldnewlabel\newlabel -\gdef\newlabel#1#2{\newlabelxx{#1}#2} -\gdef\newlabelxx#1#2#3#4#5#6{\oldnewlabel{#1}{{#2}{#3}}} -\AtEndDocument{\ifx\hyper@anchor\@undefined -\let\contentsline\oldcontentsline -\let\newlabel\oldnewlabel -\fi} -\fi} -\global\let\hyper@last\relax -\gdef\HyperFirstAtBeginDocument#1{#1} -\providecommand\HyField@AuxAddToFields[1]{} -\providecommand\HyField@AuxAddToCoFields[2]{} -\@writefile{toc}{\contentsline {paragraph}{}{2}{section*.3}} -\@writefile{toc}{\contentsline {paragraph}{}{2}{section*.5}} -\@writefile{toc}{\contentsline {paragraph}{}{2}{section*.7}} -\@writefile{toc}{\contentsline {paragraph}{}{3}{section*.9}} -\@writefile{toc}{\contentsline {paragraph}{}{3}{section*.11}} -\@writefile{toc}{\contentsline {paragraph}{}{4}{section*.13}} -\@writefile{toc}{\contentsline {paragraph}{}{4}{section*.15}} -\@writefile{toc}{\contentsline {paragraph}{}{5}{section*.17}} -\@writefile{toc}{\contentsline {paragraph}{}{5}{section*.19}} -\@writefile{toc}{\contentsline {paragraph}{}{6}{section*.22}} -\@writefile{toc}{\contentsline {paragraph}{}{6}{section*.24}} -\@writefile{toc}{\contentsline {paragraph}{}{7}{section*.26}} -\@writefile{toc}{\contentsline {paragraph}{}{7}{section*.28}} -\@writefile{toc}{\contentsline {paragraph}{}{8}{section*.32}} -\@writefile{toc}{\contentsline {paragraph}{}{8}{section*.34}} -\@writefile{toc}{\contentsline {paragraph}{}{9}{section*.36}} -\@writefile{toc}{\contentsline {paragraph}{}{9}{section*.38}} -\@writefile{toc}{\contentsline {paragraph}{}{9}{section*.40}} -\@writefile{toc}{\contentsline {paragraph}{}{10}{section*.42}} -\@writefile{toc}{\contentsline {paragraph}{}{11}{section*.47}} -\@writefile{toc}{\contentsline {paragraph}{}{20}{section*.65}} -\@writefile{toc}{\contentsline {paragraph}{}{20}{section*.67}} -\@writefile{toc}{\contentsline {paragraph}{Statistical analysis.}{20}{section*.69}} -\@writefile{toc}{\contentsline {paragraph}{}{20}{section*.71}} -\@writefile{toc}{\contentsline {paragraph}{}{21}{section*.73}} -\@writefile{toc}{\contentsline {paragraph}{}{21}{section*.75}} -\@writefile{toc}{\contentsline {paragraph}{}{21}{section*.77}} -\@writefile{toc}{\contentsline {paragraph}{}{22}{section*.79}} -\newlabel{eq:def_covariance}{{12}{22}{}{equation.0.12}{}} -\@writefile{toc}{\contentsline {paragraph}{}{22}{section*.81}} -\@writefile{toc}{\contentsline {paragraph}{}{23}{section*.83}} -\@writefile{toc}{\contentsline {paragraph}{}{23}{section*.85}} -\newlabel{eq:variance_linear_combination}{{18}{23}{}{equation.0.18}{}} -\@writefile{toc}{\contentsline {paragraph}{}{23}{section*.87}} -\@writefile{toc}{\contentsline {paragraph}{}{24}{section*.89}} -\@writefile{toc}{\contentsline {paragraph}{}{24}{section*.91}} -\@writefile{toc}{\contentsline {paragraph}{}{24}{section*.93}} -\@writefile{toc}{\contentsline {paragraph}{}{25}{section*.95}} -\@writefile{toc}{\contentsline {paragraph}{}{25}{section*.97}} -\@writefile{toc}{\contentsline {paragraph}{}{25}{section*.99}} -\newlabel{eq:central_limit_gaussian}{{19}{25}{}{equation.0.19}{}} -\@writefile{toc}{\contentsline {paragraph}{}{25}{section*.101}} -\newlabel{eq:error_exact}{{20}{25}{}{equation.0.20}{}} -\@writefile{toc}{\contentsline {paragraph}{}{26}{section*.103}} -\@writefile{toc}{\contentsline {paragraph}{}{26}{section*.105}} -\newlabel{eq:var_estimate_i_think}{{21}{26}{}{equation.0.21}{}} -\newlabel{eq:error_estimate}{{22}{26}{}{equation.0.22}{}} -\@writefile{toc}{\contentsline {paragraph}{}{27}{section*.107}} -\newlabel{eq:error_estimate_uncorrel}{{23}{27}{}{equation.0.23}{}} -\@writefile{toc}{\contentsline {paragraph}{}{27}{section*.109}} -\newlabel{eq:error_estimate_split_up}{{24}{27}{}{equation.0.24}{}} -\@writefile{toc}{\contentsline {paragraph}{}{27}{section*.111}} -\@writefile{toc}{\contentsline {paragraph}{}{28}{section*.113}} -\@writefile{toc}{\contentsline {paragraph}{}{28}{section*.115}} -\newlabel{eq:error_estimate_corr_time}{{25}{28}{}{equation.0.25}{}} -\newlabel{eq:autocorrelation_time}{{26}{28}{}{equation.0.26}{}} -\@writefile{toc}{\contentsline {paragraph}{}{28}{section*.117}} -\@writefile{toc}{\contentsline {paragraph}{}{33}{section*.130}} -\@writefile{toc}{\contentsline {paragraph}{Exercise 1.}{39}{section*.148}} -\@writefile{toc}{\contentsline {paragraph}{Exercise 2, variance of the parameters $\beta $ in linear regression.}{39}{section*.149}} -\@writefile{toc}{\contentsline {paragraph}{Exercise 3.}{40}{section*.150}} -\@writefile{toc}{\contentsline {paragraph}{Exercise 4.}{41}{section*.151}} -\gdef\minted@oldcachelist{, - default.pygstyle, - 51639A41B11E5FE7D4CD027BA48FB6C64B967B05670D715D94F4392BD3176A49.pygtex, - 4C68C697EB414B135747B9ECA18C3B5B4B967B05670D715D94F4392BD3176A49.pygtex, - 439DCAB036A38F6389948C8DF1465C424B967B05670D715D94F4392BD3176A49.pygtex, - 0A3C1B39ACFAF4BAB627404CB6156A144B967B05670D715D94F4392BD3176A49.pygtex, - F5688422A51FDCF3C06A3FF7EF8F9E6E4B967B05670D715D94F4392BD3176A49.pygtex, - FE87C84792E25A9D98329B989214E79F4B967B05670D715D94F4392BD3176A49.pygtex, - F9FF5FEA9F501D7189D0F820FC8D1D3D4B967B05670D715D94F4392BD3176A49.pygtex, - 2702C77D52D3F655EDD2BB83D8F1240B4B967B05670D715D94F4392BD3176A49.pygtex, - E81889C7775BD173862927052713983D4B967B05670D715D94F4392BD3176A49.pygtex, - 31D43D24D5F9D55728C4E563E0E557924B967B05670D715D94F4392BD3176A49.pygtex, - F6068C18D7EFD701D08693F8BD52B4664B967B05670D715D94F4392BD3176A49.pygtex, - 9CC2E80F086A0B9D080182D504A931C14B967B05670D715D94F4392BD3176A49.pygtex, - 4C6F7D24872AF7644FF40FC87BFFAB2B4B967B05670D715D94F4392BD3176A49.pygtex, - C8DBC01C383B0800E51E0923C05691E04B967B05670D715D94F4392BD3176A49.pygtex, - E06035EDB37DBFD5697CD9DD1C5CA4A34B967B05670D715D94F4392BD3176A49.pygtex, - 363FA9AE05CC4E390538E08524572CF34B967B05670D715D94F4392BD3176A49.pygtex, - 367BFC34E39C7EA712AF1384CAA96F674B967B05670D715D94F4392BD3176A49.pygtex, - 09054641A8F49E0FADA410EE6C9BC1BA4B967B05670D715D94F4392BD3176A49.pygtex, - A7435FEC44C0E9C1E9660C02CDC74B3F4B967B05670D715D94F4392BD3176A49.pygtex, - 16523CD54121DE1835E829B872835EA64B967B05670D715D94F4392BD3176A49.pygtex, - 5A860BD7323291C7CF7221BB9B86BDC74B967B05670D715D94F4392BD3176A49.pygtex, - 457F2C4C88437DDFAF88B1D28783CF034B967B05670D715D94F4392BD3176A49.pygtex, - 066BCC1A504ED48C98D58B2EC6A448284B967B05670D715D94F4392BD3176A49.pygtex, - 5D2065327E88AF636A043C8526ED982B4B967B05670D715D94F4392BD3176A49.pygtex, - B0F453236926744E43E08A3FC3D889CE4B967B05670D715D94F4392BD3176A49.pygtex, - BFFA2954B53E806314EE31A7A4153BE34B967B05670D715D94F4392BD3176A49.pygtex, - F0C6E7177EB3BF181C2BCDCF6C126D174B967B05670D715D94F4392BD3176A49.pygtex, - 679F13D40F197D86A49DDBAE2064874A4B967B05670D715D94F4392BD3176A49.pygtex, - ECE8CFF2AC201FE83D423B89AB24D84D4B967B05670D715D94F4392BD3176A49.pygtex, - 90854007E426D557D1191356516A553B4B967B05670D715D94F4392BD3176A49.pygtex, - D10574B3CE6341E3B1CE27A555FC959C4B967B05670D715D94F4392BD3176A49.pygtex, - 207A7B5C5A05397AD9CC324488E0F0A34B967B05670D715D94F4392BD3176A49.pygtex, - 0FE2839ED408ED62CECC4C3D9FE2DDE84B967B05670D715D94F4392BD3176A49.pygtex, - EAD510BC3ABCC6143355164B81A3C2ED4B967B05670D715D94F4392BD3176A49.pygtex, - EAD510BC3ABCC6143355164B81A3C2ED4B967B05670D715D94F4392BD3176A49.pygtex, - 795F82986CD7DD6E2E776380A1AFB2624B967B05670D715D94F4392BD3176A49.pygtex} diff --git a/doc/src/Regression/Regression.dlog b/doc/src/Regression/Regression.dlog deleted file mode 100644 index b34391d33..000000000 --- a/doc/src/Regression/Regression.dlog +++ /dev/null @@ -1,146 +0,0 @@ -translating doconce text in Regression.do.txt to html -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) -*** warning: math block in HTML must have space around <: -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k - - - - - - - -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis - - - - - - - - - - - - - - - - - - - - - - - -

Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis

- -

- - -

-Morten Hjorth-Jensen [1, 2] -
- -

- - -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

-

Jul 22, 2019

-
-

-









- -

Why Linear Regression (aka Ordinary Least Squares and family)

- -

-Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \). - -

- -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. - -

-









- -

Regression analysis, overarching aims

-
- -

- -

-Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. - -

-A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with - -

    -
  • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
  • -
  • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
  • -
  • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
  • -
- - The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. -
- - -

-









- -

Regression analysis, overarching aims II

-
- -

- -

-Consider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix -\( \mathbf{X} \). - -

-The matrix \( \mathbf{X} \) is called the design -matrix. Additional information of the samples is available in the -form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is -generally referred to as the response variable. The aim of -regression analysis is to explain \( \boldsymbol{y} \) in terms of -\( \boldsymbol{X} \) through a functional relationship like \( y_i = -f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of -\( f(\cdot) \) is available, it is common to assume a linear relationship -between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to -the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T} \) are the regression parameters. - -

-Linear regression gives us a set of analytical equations for the parameters \( \beta_j \). - - -

- - -

-









- -

Examples

-
- -

-In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), -consider the model we discussed for describing nuclear binding energies. - -

-There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. -Assuming -$$ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, -$$ - -we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. -This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a -\( p\times n \) matrix \( \boldsymbol{X} \). - -

-Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \) - - -

- - -

-









- -

General linear models

-
- -

-Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. - -

-Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is -$$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, -$$ - -where \( \epsilon_i \) is the error in our approximation. - - -

- - -

-









- -

Rewriting the fitting procedure as a linear algebra problem

-
- -

-For every set of values \( y_i,x_i \) we have thus the corresponding set of equations -$$ -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ -

- - -

-









- -

Rewriting the fitting procedure as a linear algebra problem, more details

-
- -

-Defining the vectors -$$ -\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -$$ - -and -$$ -\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -$$ - -and -$$ -\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -$$ - -and the design matrix -$$ -\boldsymbol{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -$$ - -we can rewrite our equations as -$$ -\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. -$$ - -The above design matrix is called a Vandermonde matrix. -

- - -

-









- -

Generalizing the fitting procedure as a linear algebra problem

-
- -

- -

-We are obviously not limited to the above polynomial expansions. We -could replace the various powers of \( x \) with elements of Fourier -series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j -x_i)} \), or time series or other orthogonal functions. For every set -of values \( y_i,x_i \) we can then generalize the equations to - -$$ -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ - -

-Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case! -

- - -

-









- -

Generalizing the fitting procedure as a linear algebra problem

-
- -

-We redefine in turn the matrix \( \boldsymbol{X} \) as -$$ -\boldsymbol{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -$$ - -and without loss of generality we rewrite again our equations as -$$ -\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. -$$ - -The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? -

- - -

-









- -

Optimizing our parameters

-
- -

-We have defined the matrix \( \boldsymbol{X} \) via the equations -$$ -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -$$ - -

-As we noted above, we stayed with a system with the design matrix - \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define -our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. - - -

- - -

-









- -

Our model for the nuclear binding energies

- -

-In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. - -

-We restate the parts of the code we are most interested in. -

- - -

# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("MassEval2016.dat"),'r')
-
-
-# Read the experimental data with Pandas
-Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
-              names=('N', 'Z', 'A', 'Element', 'Ebinding'),
-              widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
-              header=39,
-              index_col=False)
-
-# Extrapolated values are indicated by '#' in place of the decimal place, so
-# the Ebinding column won't be numeric. Coerce to float and drop these entries.
-Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
-Masses = Masses.dropna()
-# Convert from keV to MeV.
-Masses['Ebinding'] /= 1000
-
-# Group the DataFrame by nucleon number, A.
-Masses = Masses.groupby('A')
-# Find the rows of the grouped DataFrame with the maximum binding energy.
-Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
-A = Masses['A']
-Z = Masses['Z']
-N = Masses['N']
-Element = Masses['Element']
-Energies = Masses['Ebinding']
-
-# Now we set up the design matrix X
-X = np.zeros((len(A),5))
-X[:,0] = 1
-X[:,1] = A
-X[:,2] = A**(2.0/3.0)
-X[:,3] = A**(-1.0/3.0)
-X[:,4] = A**(-1.0)
-# Then nice printout using pandas
-DesignMatrix = pd.DataFrame(X)
-DesignMatrix.index = A
-DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
-display(DesignMatrix)
-
-

-With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as -$$ -\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, -$$ - -throughout these lectures. - -

-









- -

Optimizing our parameters, more details

-
- -

-With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as -$$ -\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, -$$ - -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely -$$ -C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, -$$ - -or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as -$$ -C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}. -$$ - -This function is one possible way to define the so-called cost function. - -

-It is also common to define -the function \( Q \) as - -$$ -C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, -$$ - -since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out. -

- - -

-









- -

Interpretations and optimizing our parameters

-
- -

- -

-The function -$$ -C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, -$$ - -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) -$$ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -$$ - -

-where \( \langle y_i \rangle \) is the mean value. Keep in mind also that -till now we have treated \( y_i \) as the exact value. Normally, the -response (dependent or outcome) variable \( y_i \) the outcome of a -numerical experiment or another type of experiment and is thus only an -approximation to the true value. It is then always accompanied by an -error estimate, often limited to a statistical error estimate given by -the standard deviation discussed earlier. In the discussion here we -will treat \( y_i \) as our exact value for the response variable. - -

-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem -$$ -{\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\}. -$$ - -In practical terms it means we will require -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -$$ - -which results in -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -$$ - -or in a matrix-vector form as -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). -$$ - - -

- - -

-









- -

Interpretations and optimizing our parameters

-
- -

-We can rewrite -$$ -\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), -$$ - -as -$$ -\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, -$$ - -and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution -$$ -\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ - -

-We note also that since our design matrix is defined as \( \boldsymbol{X}\in -{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in -{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), -in our case \( p=5 \) meaning that we end up with inverting a small -\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional -matrices to invert. The methods discussed here and for many other -supervised learning algorithms like classification with logistic -regression or support vector machines, exhibit dimensionalities which -allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \). - - -

- - -

-









- -

Interpretations and optimizing our parameters

-
- -

-The residuals \( \boldsymbol{\epsilon} \) are in turn given by -$$ -\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, -$$ - -and with -$$ -\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, -$$ - -we have -$$ -\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, -$$ - -meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. - - -

- - -

-Let us now return to our nuclear binding energies and simply code the above equations. - -

-









- -

Own code for Ordinary Least Squares

- -

-It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to -write -

- - -

# matrix inversion to find beta
-beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
-# and then make the prediction
-ytilde = X @ beta
-
-

-Alternatively, you can use the least squares functionality in Numpy as -

- - -

fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
-ytildenp = np.dot(fit,X.T)
-
-

-And finally we plot our fit with and compare with data -

- - -

Masses['Eapprox']  = ytilde
-# Generate a plot comparing the experimental with the fitted values values.
-fig, ax = plt.subplots()
-ax.set_xlabel(r'$A = N + Z$')
-ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
-ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
-            label='Ame2016')
-ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
-            label='Fit')
-ax.legend()
-save_fig("Masses2016OLS")
-plt.show()
-
-

-









- -

Adding error analysis and training set up

- -

-We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. -Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as -

- - -

def R2(y_data, y_model):
-    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
-
-

-and we would be using it as -

- - -

print(R2(Energies,ytilde))
-
-

-We can easily add our MSE score as -

- - -

def MSE(y_data,y_model):
-    n = np.size(y_model)
-    return np.sum((y_data-y_model)**2)/n
-
-print(MSE(Energies,ytilde))
-
-

-and finally the relative error as -

- - -

def RelativeError(y_data,y_model):
-    return abs((y_data-y_model)/y_data)
-print(RelativeError(Energies, ytilde))
-
-

-









- -

The \( \chi^2 \) function

-
- -

- -

-Normally, the response (dependent or outcome) variable \( y_i \) is the -outcome of a numerical experiment or another type of experiment and is -thus only an approximation to the true value. It is then always -accompanied by an error estimate, often limited to a statistical error -estimate given by the standard deviation discussed earlier. In the -discussion here we will treat \( y_i \) as our exact value for the -response variable. - -

-Introducing the standard deviation \( \sigma_i \) for each measurement -\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) -as - -$$ -\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, -$$ - -where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - - -

- - -

-









- -

The \( \chi^2 \) function

-
- -

- -

-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -$$ - -which results in -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -$$ - -or in a matrix-vector form as -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). -$$ - -where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \). -

- - -

-









- -

The \( \chi^2 \) function

-
- -

- -

-We can rewrite -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), -$$ - -as -$$ -\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, -$$ - -and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution -$$ -\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. -$$ -

- - -

-









- -

The \( \chi^2 \) function

-
- -

- -

-If we then introduce the matrix -$$ -\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, -$$ - -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) -$$ -\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} -$$ - -We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise) -$$ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -$$ - -resulting in -$$ -\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! -$$ -

- - -

-









- -

The \( \chi^2 \) function

-
- -

-The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write -$$ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -$$ - -By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -$$ - -and -$$ -\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -$$ -

- - -

-









- -

The \( \chi^2 \) function

-
- -

- -

-For a linear fit (a first-order polynomial) we don't need to invert a matrix!! -Defining -$$ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -$$ - - -$$ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -$$ - - -$$ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -$$ - - -$$ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -$$ - - -$$ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -$$ - -

-we obtain - -$$ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -$$ - - -$$ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -$$ - -

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

- - -

-









- -

Fitting an Equation of State for Dense Nuclear Matter

- -

-Before we continue, let us introduce yet another example. We are going to fit the -nuclear equation of state using results from many-body calculations. -The equation of state we have made available here, as function of -density, has been derived using modern nucleon-nucleon potentials with -the addition of three-body -forces. This -time the file is presented as a standard csv file. - -

-The beginning of the Python code here is similar to what you have seen before, -with the same initializations and declarations. We use also pandas -again, rather extensively in order to organize our data. - -

-The difference now is that we use Scikit-Learn's regression tools -instead of our own matrix inversion implementation. Furthermore, we -sneak in Ridge regression (to be discussed below) which includes a -hyperparameter \( \lambda \), also to be explained below. - -

-









- -

The code

- -

- - -

# Common imports
-import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-import matplotlib.pyplot as plt
-import sklearn.linear_model as skl
-from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as  csv file and organize the data into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-#  The design matrix now as function of various polytrops
-X = np.zeros((len(Density),4))
-X[:,3] = Density**(4.0/3.0)
-X[:,2] = Density
-X[:,1] = Density**(2.0/3.0)
-X[:,0] = 1
-
-# We use now Scikit-Learn's linear regressor and ridge regressor
-# OLS part
-clf = skl.LinearRegression().fit(X, Energies)
-ytilde = clf.predict(X)
-EoS['Eols']  = ytilde
-# The mean squared error                               
-print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
-# Explained variance score: 1 is perfect prediction                                 
-print('Variance score: %.2f' % r2_score(Energies, ytilde))
-# Mean absolute error                                                           
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
-print(clf.coef_, clf.intercept_)
-
-# The Ridge regression with a hyperparameter lambda = 0.1
-_lambda = 0.1
-clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
-yridge = clf_ridge.predict(X)
-EoS['Eridge']  = yridge
-# The mean squared error                               
-print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
-# Explained variance score: 1 is perfect prediction                                 
-print('Variance score: %.2f' % r2_score(Energies, yridge))
-# Mean absolute error                                                           
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
-print(clf_ridge.coef_, clf_ridge.intercept_)
-
-fig, ax = plt.subplots()
-ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
-ax.set_ylabel(r'Energy per particle')
-ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,
-            label='Theoretical data')
-ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
-            label='OLS')
-ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
-            label='Ridge $\lambda = 0.1$')
-ax.legend()
-save_fig("EoSfitting")
-plt.show()
-
-

-The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. Can you give an interpretation of the various powers of \( \rho \)? - -

-We note also that there is a small deviation between the -standard OLS and the Ridge regression at higher densities. We discuss this in more detail -below. - -

-









- -

Splitting our Data in Training and Test data

- -

-It is normal in essentially all Machine Learning studies to split the -data in a training set and a test set (sometimes also an additional -validation set). Scikit-Learn has an own function for this. There -is no explicit recipe for how much data should be included as training -data and say test data. An accepted rule of thumb is to use -approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will -postpone a discussion of this splitting to the end of these notes and -our discussion of the so-called bias-variance tradeoff. Here we -limit ourselves to repeat the above equation of state fitting example -but now splitting the data into a training set and a test set. - -

- - -

import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from sklearn.model_selection import train_test_split
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
-    os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
-    os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
-    os.makedirs(DATA_ID)
-
-def image_path(fig_id):
-    return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
-    return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
-    plt.savefig(image_path(fig_id) + ".png", format='png')
-
-def R2(y_data, y_model):
-    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
-def MSE(y_data,y_model):
-    n = np.size(y_model)
-    return np.sum((y_data-y_model)**2)/n
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as  csv file and organized into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-#  The design matrix now as function of various polytrops
-X = np.zeros((len(Density),5))
-X[:,0] = 1
-X[:,1] = Density**(2.0/3.0)
-X[:,2] = Density
-X[:,3] = Density**(4.0/3.0)
-X[:,4] = Density**(5.0/3.0)
-# We split the data in test and training data
-X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
-# matrix inversion to find beta
-beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
-# and then make the prediction
-ytilde = X_train @ beta
-print("Training R2")
-print(R2(y_train,ytilde))
-print("Training MSE")
-print(MSE(y_train,ytilde))
-ypredict = X_test @ beta
-print("Test R2")
-print(R2(y_test,ypredict))
-print("Test MSE")
-print(MSE(y_test,ypredict))
-
-

-









- -

The singular value decomposition

- -

-

- -

- -

-The examples we have looked at so far are cases where we normally can -invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we -did both for the masses and the fitting of the equation of state, -leads to row vectors of the design matrix which are essentially -orthogonal due to the polynomial character of our model. This may -however not the be case in general and a standard matrix inversion -algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit -the coupling constant of the widely used Ising model. -There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. - -

-This is given by the Singular Value Decomposition algorithm, perhaps -the most powerful linear algebra algorithm. Let us look at a -different example where we may have problems with the standard matrix -inversion algorithm. Thereafter we dive into the math of the SVD. - - -

- - -

-









- -

The Ising model

- -

-The one-dimensional Ising model with nearest neighbor interaction, no -external field and a constant coupling constant \( J \) is given by - -$$ -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\label{_auto1} -\end{align} -$$ - -

-where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins -in the system is determined by \( L \). For the one-dimensional system -there is no phase transition. - -

-We will look at a system of \( L = 40 \) spins with a coupling constant of -\( J = 1 \). To get enough training data we will generate 10000 states -with their respective energies. - -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from mpl_toolkits.axes_grid1 import make_axes_locatable
-import seaborn as sns
-import scipy.linalg as scl
-from sklearn.model_selection import train_test_split
-import tqdm
-sns.set(color_codes=True)
-cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
-
-L = 40
-n = int(1e4)
-
-spins = np.random.choice([-1, 1], size=(n, L))
-J = 1.0
-
-energies = np.zeros(n)
-
-for i in range(n):
-    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-
-

-Here we use ordinary least squares -regression to predict the energy for the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use linear regression to fit a value for -the coupling constant to achieve this. - -

-









- -

Reformulating the problem to suit regression

- -

-A more general form for the one-dimensional Ising model is - -$$ -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\label{_auto2} -\end{align} -$$ - -

-Here we allow for interactions beyond the nearest neighbors and a state dependent -coupling constant. This latter expression can be formulated as -a matrix-product -$$ -\begin{align} - \boldsymbol{H} = \boldsymbol{X} J, -\label{_auto3} -\end{align} -$$ - -

-where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the -elements \( -J_{jk} \). This form of writing the energy fits perfectly -with the form utilized in linear regression, that is - -$$ -\begin{align} - \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}, -\label{_auto4} -\end{align} -$$ - -

-We split the data in training and test data as discussed in the previous example - -

- - -

X = np.zeros((n, L ** 2))
-for i in range(n):
-    X[i] = np.outer(spins[i], spins[i]).ravel()
-y = energies
-X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
-
-

-









- -

Linear regression

- -

-In the ordinary least squares method we choose the cost function - -$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}. -\label{_auto5} -\end{align} -$$ - -

-We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above. -This yields the expression for \( \boldsymbol{\beta} \) to be - -$$ - \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}}, -$$ - -

-which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist -an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an -intercept, i.e., a constant term, we must make sure that the -first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here - -

- - -

X_train_own = np.concatenate(
-    (np.ones(len(X_train))[:, np.newaxis], X_train),
-    axis=1
-)
-X_test_own = np.concatenate(
-    (np.ones(len(X_test))[:, np.newaxis], X_test),
-    axis=1
-)
-
-

- - -

def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
-    return scl.inv(x.T @ x) @ (x.T @ y)
-beta = ols_inv(X_train_own, y_train)
-
-

-









- -

Singular Value decomposition

- -

-Doing the inversion directly turns out to be a bad idea since the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular -value decomposition. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as - -$$ - \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y}, -$$ - -

-where the pseudoinverse of \( \boldsymbol{X} \) is given by - -$$ - \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}. -$$ - -

-Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \), -where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below). -where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for -\( \omega \) to -$$ -\begin{align} - \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}. -\label{_auto6} -\end{align} -$$ - -

-Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a -general matrix. Instead, doing \( QR \)-factorization and solving the -linear system as an equation would reduce this down to -\( \mathcal{O}(n^2) \) operations. - -

- - -

def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
-    u, s, v = scl.svd(x)
-    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
-
-

- - -

beta = ols_svd(X_train_own,y_train)
-
-

-When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here - -

- - -

J = beta[1:].reshape(L, L)
-
-

-A way of looking at the coefficients in \( J \) is to plot the matrices as images. - -

- - -

fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J, **cmap_args)
-plt.title("OLS", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-plt.show()
-
-

-It is interesting to note that OLS -considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as -valid matrix elements for \( J \). -In our discussion below on hyperparameters and Ridge and Lasso regression we will see that -this problem can be removed, partly and only with Lasso regression. - -

-In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? - -

-









- -

Linear Regression Problems

- -

-One of the typical problems we encounter with linear regression, in particular -when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \) -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix -$$ -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} -$$ - -

-The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. - -

-Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{x} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -$$ -\begin{align*} -\boldsymbol{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -$$ - -We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. -This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero. - -

-









- -

Fixing the singularity

- -

-If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem -$$ -\begin{align} -\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, -\label{_auto7} -\end{align} -$$ - -has linearly dependent column vectors, we will not be able to compute the inverse -of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \). -The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits. -This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters \( \beta_i \) cannot be estimated. - -

-A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change -$$ -\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, -$$ - -where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later. - -

-









- -

Basic math of the SVD

- -

-From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is -a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \) -we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \). -The matrix has then a set of eigenpairs - -$$ -(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), -$$ - -and the eigenvalues are given by the diagonal matrix -$$ -\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). -$$ - -The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) -$$ -\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ - -with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \). - -

-Not all square matrices are diagonalizable. A matrix like the one discussed above -$$ -\boldsymbol{X} = \begin{bmatrix} -1& -1 \\ -1& -1\\ -\end{bmatrix} -$$ - -is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition -\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled. - -

-









- -

The SVD, a Fantastic Algorithm

- -

-However, and this is the strength of the SVD algorithm, any general -matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and -two orthogonal/unitary matrices. The Singular Value Decompostion -(SVD) theorem -states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in -terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( n\times n \) -and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has -dimensionality \( m \times m \) and the last dimensionality \( n\times n \). -We have then - -$$ -\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T -$$ - -

-As an example, the above defective matrix can be decomposed as - -$$ -\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ - -

-with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). -The SVD exits always! - -

-









- -

Another Example

- -

-Consider the following matrix which can be SVD decomposed as - -$$ -\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. -$$ - -

-This is a \( 3\times 2 \) matrix which is decomposed in terms of a -\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see -that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?). - -

-And the SVD -decomposition (singular values) gives eigenvalues -\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), the -eigenvalues (singular values) are zero. - -

-In the general case, where our design matrix \( \boldsymbol{X} \) has dimension -\( n\times p \), the matrix is thus decomposed into an \( n\times n \) -orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) -and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) -singular values \( \sigma_i\lg 0 \) on the main diagonal and zeros filling -the rest of the matrix. There are at most \( p \) singular values -assuming that \( n > p \). In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have \( p > n \). These are often cases that lead to -near singular or singular matrices. - -

-The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors. - -

-









- -

Economy-size SVD

- -

-If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n -\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however -irrelevant in our calculations since they are multiplied with the -zeros in \( \boldsymbol{\Sigma} \). - -

-The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns -in either \( \boldsymbol{U} \) or \( \boldsymbol{V} \) that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. - -

-If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). -If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). -The \( n=p \) case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. - -

-









- -

Mathematical Properties

- -

-There are several interesting mathematical properties which will be -relevant when we are going to discuss the differences between say -ordinary least squares (OLS) and Ridge regression. - -

-We have from OLS that the parameters of the linear approximation are given by -$$ -\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ - -

-The matrix to invert can be rewritten in terms of our SVD decomposition as - -$$ -\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. -$$ - -Using the orthogonality properties of \( \boldsymbol{U} \) we have - -$$ -\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T, -$$ - -with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared. - -

-This means that -$$ -(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D}, -$$ - -that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that -$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}, -$$ - -that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same. - -

-Going back to our OLS equation we have -$$ -\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. -$$ - -We will come back to this expression when we discuss Ridge regression. - -

-









- -

Ridge and LASSO Regression

- -

-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}\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 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}. -$$ - -

-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 - -$$ -{\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. -$$ - -

-









- -

More on Ridge Regression

- -

-Using the matrix-vector expression for Ridge regression, - -$$ -C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta}, -$$ - -

-by 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 - -$$ -\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. - -

-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 -are rather interesting. - -

-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had -$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}. -$$ - -

-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as -$$ -\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} -$$ - -

-For Ridge regression this becomes - -$$ -\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\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} \). - -

-









- -

Interpreting the Ridge results

- -

-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} \). - -

-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. -Actually, calculating the variance of \( \boldsymbol{X}\boldsymbol{v}_j \) shows that this quantity is equal to \( \sigma_j^2/n \). -With a parameter \( \lambda \) we can thus shrink the role of specific parameters. - -

-









- -

More interpretations

- -

-For the sake of simplicity, let us assume that the design matrix is orthonormal, that is - -$$ -\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. -$$ - -

-In this case the standard OLS results in -$$ -\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^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. - -

-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. - -

-









- -

Where are we going?

- -

-Before we proceed, we need to rethink what we have been doing. In our -eager to fit the data, we have omitted several important elements in -our regression analysis. In what follows we will - -

    -
  1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
  2. -
  3. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
  4. -
- -This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. - -

-









- -

Resampling methods

-
- -

-Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. -

- - -

-









- -

Resampling approaches can be computationally expensive

-
- -

- -

-Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. - - -

- - -

-









- -

Why resampling methods ?

-
-Statistical analysis. -

- -

    -
  • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
  • -
  • The results can be analysed with the same statistical tools as we would use analysing experimental data.
  • -
  • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
  • -
-
- - -

-









- -

Statistical analysis

-
- -

- -

    -
  • As in other experiments, many numerical experiments have two classes of errors:
  • - -
      -
    • Statistical errors
    • -
    • Systematical errors
    • -
    - -
  • Statistical errors can be estimated using standard tools from statistics
  • -
  • Systematical errors are method specific and must be treated differently from case to case.
  • -
-
- - -

-









- -

Statistics

-
- -

-The probability distribution function (PDF) is a function -\( p(x) \) on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of \( X \) occur: -$$ -p(x) = \mathrm{prob}(X=x) -$$ - -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around \( x \) to be \( p(x)dx \). The continuous function \( p(x) \) then gives us -the density of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval \( [a,\,b] \) is then just the integral: -$$ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx -$$ - -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. -

- - -

-









- -

Statistics, moments

-
- -

-A particularly useful class of special expectation values are the -moments. The \( n \)-th moment of the PDF \( p \) is defined as -follows: -$$ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx -$$ - -The zero-th moment \( \langle 1\rangle \) is just the normalization condition of -\( p \). The first moment, \( \langle x\rangle \), is called the mean of \( p \) -and often denoted by the letter \( \mu \): -$$ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx -$$ -

- - -

-









- -

Statistics, central moments

-
- -

-A special version of the moments is the set of central moments, -the n-th central moment defined as: -$$ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -$$ - -The zero-th and first central moments are both trivial, equal \( 1 \) and -\( 0 \), respectively. But the second central moment, known as the -variance of \( p \), is of particular interest. For the stochastic -variable \( X \), the variance is denoted as \( \sigma^2_X \) or \( \mathrm{var}(X) \): -$$ -\begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx -\label{_auto8}\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx -\label{_auto9}\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 -\label{_auto10}\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\label{_auto11} -\end{align} -$$ - -The square root of the variance, \( \sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle} \) is called the standard deviation of \( p \). It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the spread of \( p \) around its mean. -

- - -

-









- -

Statistics, covariance

-
- -

-Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set \( \{X_i\} \) of \( n \) -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF \( P(x_1,\dots,x_n) \). The covariance of two -of the stochastic variables, \( X_i \) and \( X_j \), is defined as follows: -$$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\label{eq:def_covariance} -\end{align} -$$ - -with -$$ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -$$ -

- - -

-









- -

Statistics, more covariance

-
- -

-If we consider the above covariance as a matrix \( C_{ij}=\mathrm{cov}(X_i,\,X_j) \), then the diagonal elements are just the familiar -variances, \( C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i) \). It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables \( X_i \) and -\( X_j \), (\( i\neq j \)): -$$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\label{_auto12}\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle -\label{_auto13}\\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle -\label{_auto14}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle -\label{_auto15}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\label{_auto16} -\end{align} -$$ -

- - -

-









- -

Statistics, independent variables

-
- -

-If \( X_i \) and \( X_j \) are independent, we get -\( \langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle \), resulting in \( \mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j) \). - -

-Also useful for us is the covariance of linear combinations of -stochastic variables. Let \( \{X_i\} \) and \( \{Y_i\} \) be two sets of -stochastic variables. Let also \( \{a_i\} \) and \( \{b_i\} \) be two sets of -scalars. Consider the linear combination: -$$ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j -$$ - -By the linearity of the expectation value -$$ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) -$$ -

- - -

-









- -

Statistics, more variance

-
- -

-Now, since the variance is just \( \mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i) \), we get -the variance of the linear combination \( U = \sum_i a_i X_i \): -$$ -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\label{eq:variance_linear_combination} -\end{equation} -$$ - -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -$$ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -$$ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -which will become very useful in our study of the error in the mean -value of a set of measurements. -

- - -

-









- -

Statistics and stochastic processes

-
- -

-A stochastic process is a process that produces sequentially a -chain of values: -$$ -\{x_1, x_2,\dots\,x_k,\dots\}. -$$ - -We will call these -values our measurements and the entire set as our measured -sample. The action of measuring all the elements of a sample -we will call a stochastic experiment since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF \( p_X^{\phantom X}(x) \), where \( X \) is just the formal symbol for the -stochastic variable whose PDF is \( p_X^{\phantom X}(x) \). Instead of -trying to determine the full distribution \( p \) we are often only -interested in finding the few lowest moments, like the mean -\( \mu_X^{\phantom X} \) and the variance \( \sigma_X^{\phantom X} \). -

- - -

- - -

Statistics and sample variables

-
- -

-In practical situations a sample is always of finite size. Let that -size be \( n \). The expectation value of a sample, the sample mean, is then defined as follows: -$$ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -$$ - -The sample variance is: -$$ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -$$ - -its square root being the standard deviation of the sample. The -sample covariance is: -$$ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -$$ -

- - -

-









- -

Statistics, sample variance and covariance

-
- -

-Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq. \eqref{eq:def_covariance} is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. - -

-These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean \( \mu_X \), variance \( \mathrm{var}(X) \) -and covariance \( \mathrm{cov}(X,Y) \). -

- - -

-









- -

Statistics, law of large numbers

-
- -

-The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean \( \mu_X^{\phantom X} \) of the chosen PDF: -$$ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} -$$ - -The sample mean \( \bar{x}_n \) works therefore as an estimate of the true -mean \( \mu_X^{\phantom X} \). - -

-What we need to find out is how good an approximation \( \bar{x}_n \) is to -\( \mu_X^{\phantom X} \). In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the error of the sample mean, or -just sample error, and denote it by \( \mathrm{err}_X^{\phantom X} \). In -practice, we will only be able to produce an estimate of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. -

- - -

-









- -

Statistics, more on sample error

-
- -

-Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements \( x_i \) -can be associated with its own stochastic variable \( X_i \). The -stochastic variable \( \overline X_n \) for the sample mean \( \bar{x}_n \) is -then just a linear combination, already familiar to us: -$$ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i -$$ - -All the coefficients are just equal \( 1/n \). The PDF of \( \overline X_n \), -denoted by \( p_{\overline X_n}(x) \) is the desired PDF of the sample -means. -

- - -

-









- -

Statistics

-
- -

-The probability density of obtaining a sample mean \( \bar x_n \) -is the product of probabilities of obtaining arbitrary values \( x_1, -x_2,\dots,x_n \) with the constraint that the mean of the set \( \{x_i\} \) -is \( \bar x_n \): -$$ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 -$$ - -And in particular we are interested in its variance \( \mathrm{var}(\overline X_n) \). -

- - -

-









- -

Statistics, central limit theorem

-
- -

-It is generally not possible to express \( p_{\overline X_n}(x) \) in a -closed form given an arbitrary PDF \( p_X^{\phantom X} \) and a number -\( n \). But for the limit \( n\to\infty \) it is possible to make an -approximation. The very important result is called the central limit theorem. It tells us that as \( n \) goes to infinity, -\( p_{\overline X_n}(x) \) approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, \( \mu_{X}^{\phantom X} \) -and \( \sigma_{X}^{2} \), respectively: -$$ -\begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\label{eq:central_limit_gaussian} -\end{equation} -$$ -

- - -

-









- -

Statistics, more technicalities

-
- -

-The desired variance -\( \mathrm{var}(\overline X_n) \), i.e. the sample error squared -\( \mathrm{err}_X^2 \), is given by: -$$ -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\label{eq:error_exact} -\end{equation} -$$ - -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -\( \mu_{X_i}^{\phantom X} \) of the stochastic variables \( X_i \). To -calculate these requires that we know the true multivariate PDF of all -the \( X_i \). But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the \( X_i \), estimating all properties of -\( X_i \) through the measurements of the sample. -

- - -

-









- -

Statistics

-
- -

-Our estimate of \( \mu_{X_i}^{\phantom X} \) is then the sample mean \( \bar x \) -itself, in accordance with the the central limit theorem: -$$ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x -$$ - -Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an -estimate of the covariance in Eq. \eqref{eq:error_exact} -$$ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, -$$ - -resulting in -$$ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) -$$ -

- - -

-









- -

Statistics and sample variance

-
- -

-By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables \( X_i \) -$$ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, -$$ - -which is approximated as -$$ -\begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\label{eq:var_estimate_i_think} -\end{equation} -$$ - -

-Now we can calculate an estimate of the error -\( \mathrm{err}_X^{\phantom X} \) of the sample mean \( \bar x_n \): -$$ -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\label{eq:error_estimate} -\end{align} -$$ - -which is nothing but the sample covariance divided by the number of -measurements in the sample. -

- - -

-









- -

Statistics, uncorrelated results

-
- -

- -

-In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables \( X_i \) are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: -$$ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), -$$ - -resulting in -$$ -\begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\label{eq:error_estimate_uncorrel} -\end{equation} -$$ - -where in the second step we have used Eq. \eqref{eq:var_estimate_i_think}. -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. -

- - -

-









- -

Statistics, computations

-
- -

-For computational purposes one usually splits up the estimate of -\( \mathrm{err}_X^2 \), given by Eq. \eqref{eq:error_estimate}, into two -parts -$$ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), -$$ - -which equals -$$ -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) -\label{eq:error_estimate_split_up} -\end{equation} -$$ - -The first term is the same as the error in the uncorrelated case, -Eq. \eqref{eq:error_estimate_uncorrel}. This means that the second -term accounts for the error correction due to correlation between the -measurements. For uncorrelated measurements this second term is zero. -

- - -

-









- -

Statistics, more on computations of errors

-
- -

-Computationally the uncorrelated first term is much easier to treat -efficiently than the second. -$$ -\mathrm{var}(x) = \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)^2 = -\left(\frac{1}{n}\sum_{k=1}^n x_k^2\right) - \bar x_n^2 -$$ - -We just accumulate separately the values \( x^2 \) and \( x \) for every -measurement \( x \) we receive. The correlation term, though, has to be -calculated at the end of the experiment since we need all the -measurements to calculate the cross terms. Therefore, all measurements -have to be stored throughout the experiment. -

- - -

-









- -

Statistics, wrapping up 1

-
- -

-Let us analyze the problem by splitting up the correlation term into -partial sums of the form: -$$ -f_d = \frac{1}{n-d}\sum_{k=1}^{n-d}(x_k - \bar x_n)(x_{k+d} - \bar x_n) -$$ - -The correlation term of the error can now be rewritten in terms of -\( f_d \) -$$ -\frac{2}{n}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) = -2\sum_{d=1}^{n-1} f_d -$$ - -The value of \( f_d \) reflects the correlation between measurements -separated by the distance \( d \) in the sample samples. Notice that for -\( d=0 \), \( f \) is just the sample variance, \( \mathrm{var}(x) \). If we divide \( f_d \) -by \( \mathrm{var}(x) \), we arrive at the so called autocorrelation function -$$ -\kappa_d = \frac{f_d}{\mathrm{var}(x)} -$$ - -which gives us a useful measure of pairwise correlations -starting always at \( 1 \) for \( d=0 \). -

- - -

-









- -

Statistics, final expression

-
- -

-The sample error (see eq. \eqref{eq:error_estimate_split_up}) can now be -written in terms of the autocorrelation function: -$$ -\begin{align} -\mathrm{err}_X^2 &= -\frac{1}{n}\mathrm{var}(x)+\frac{2}{n}\cdot\mathrm{var}(x)\sum_{d=1}^{n-1} -\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=& -\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\ -&=\frac{\tau}{n}\cdot\mathrm{var}(x) -\label{eq:error_estimate_corr_time} -\end{align} -$$ - -and we see that \( \mathrm{err}_X \) can be expressed in terms the -uncorrelated sample variance times a correction factor \( \tau \) which -accounts for the correlation between measurements. We call this -correction factor the autocorrelation time: -$$ -\begin{equation} -\tau = 1+2\sum_{d=1}^{n-1}\kappa_d -\label{eq:autocorrelation_time} -\end{equation} -$$ -

- - -

-









- -

Statistics, effective number of correlations

-
- -

-For a correlation free experiment, \( \tau \) -equals 1. From the point of view of -eq. \eqref{eq:error_estimate_corr_time} we can interpret a sequential -correlation as an effective reduction of the number of measurements by -a factor \( \tau \). The effective number of measurements becomes: -$$ -n_\mathrm{eff} = \frac{n}{\tau} -$$ - -To neglect the autocorrelation time \( \tau \) will always cause our -simple uncorrelated estimate of \( \mathrm{err}_X^2\approx \mathrm{var}(x)/n \) to -be less than the true sample error. The estimate of the error will be -too good. On the other hand, the calculation of the full -autocorrelation time poses an efficiency problem if the set of -measurements is very large. -

- - -

- - -

Linking the regression analysis with a statistical interpretation

- -

-Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. -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. - -

-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 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 \). - -

-









- -

Assumptions made

- -

-The assumption we have made here can be summarized as (and this is going to 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 describes our data -$$ -\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}. -$$ - -

-









- -

Expectation value and variance

- -

-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 -$$ -\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). - -

-









- -

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

- -

-With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value -$$ -\mathbb{E}(\boldsymbol{\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}. -$$ - -This means that the estimator of the regression parameters is unbiased. - -

-We can also calculate the variance - -

-The variance of \( \boldsymbol{\beta} \) is -$$ -\begin{eqnarray*} -\mbox{Var}(\boldsymbol{\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: -\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{ -[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to -construct a confidence interval for the estimates. - -

-In a similar way, we cna obtain analytical expressions for say the -expectation values of the parameters \( \boldsymbol{\beta} \) and their variance -when we employ Ridge regression, and thereby 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 - -$$ -\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. - -

- - -

Cross-validation

- -

-Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e. the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. - -

-The setting of original and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the -training set, plays the role of original data on which the model is -built. The second of these data sets, called the test set, plays the -role of the novel data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of \( \lambda \) using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. - -

-









- -

Computationally expensive

- -

-The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: - -

- - - -

Various steps in cross-validation

- -

-When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this \( k \)-fold cross-validation structures the data splitting. The -samples are divided into \( k \) more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the \( k \) subsets -involves a degree of randomness. This may be fully excluded when -choosing \( k=n \). This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -

- - -

How to set up the cross-validation for Ridge and/or Lasso

- - - -$$ -\begin{align*} -\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} -\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} -\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} -\end{align*} -$$ - - - - -$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ - - - - -









- -

Resampling methods: Jackknife and Bootstrap

- -

-Two famous -resampling methods are the independent bootstrap and the jackknife. - -

-The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as the dependent bootstrap. - -

-The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of \( \overline{X} \) (which often is the case), then there is no -need for bootstrapping. - -

-









- -

Resampling methods: Jackknife

- -

-The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \boldsymbol{x}_i \) denote the vector -$$ -\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ - -

-which equals the vector \( \boldsymbol{x} \) with the exception that observation -number \( i \) is left out. Using this notation, define -\( \widehat{\theta}_i \) to be the estimator -\( \widehat{\theta} \) computed using \( \vec{X}_i \). - -

-









- -

Jackknife code example

-

- - -

from numpy import *
-from numpy.random import randint, randn
-from time import time
-
-def jackknife(data, stat):
-    n = len(data);t = zeros(n); inds = arange(n); t0 = time()
-    ## 'jackknifing' by leaving out an observation for each i                                                                                                                      
-    for i in range(n):
-        t[i] = stat(delete(data,i) )
-
-    # analysis                                                                                                                                                                     
-    print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
-    print("original           bias      std. error")
-    print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
-
-    return t
-
-
-# Returns mean of data samples                                                                                                                                                     
-def stat(data):
-    return mean(data)
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# jackknife returns the data sample                                                                                                                                                
-t = jackknife(x, stat)
-
-

-









- -

Resampling methods: Bootstrap

-
- -

-Bootstrapping is a nonparametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: - -

    -
  1. The bootstrap is quite general, although there are some cases in which it fails.
  2. -
  3. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
  4. -
  5. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
  6. -
  7. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
  8. -
-
- - -

-









- -

Resampling methods: Bootstrap background

- -

-Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, -\( \widehat{\theta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to -estimate \( p(\boldsymbol{t}) \) by the relative frequency of -\( \widehat{\theta} \). You can think of this as using a histogram -in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely -resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point -estimators. - -

-









- -

Resampling methods: More Bootstrap background

- -

-In the case that \( \widehat{\theta} \) has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of \( X_i \), \( p(x) \), had been known, then it would have -been straight forward to do this by: - -

    -
  1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
  2. -
  3. Then using these numbers, we could compute a replica of \( \widehat{\theta} \) called \( \widehat{\theta}^* \).
  4. -
- -By repeated use of (1) and (2), many -estimates of \( \widehat{\theta} \) could have been obtained. The -idea is to use the relative frequency of \( \widehat{\theta}^* \) -(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). - -

-









- -

Resampling methods: Bootstrap approach

- -

-But -unless there is enough information available about the process that -generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general -unknown. Therefore, Efron in 1979 asked the -question: What if we replace \( p(x) \) by the relative frequency -of the observation \( X_i \); if we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - -

-Instead of generating the histogram for the relative -frequency of the observation \( X_i \), just draw the values -\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector -\( \boldsymbol{X} \). - -

-









- -

Resampling methods: Bootstrap steps

- -

-The independent bootstrap works like this: - -

    -
  1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
  2. -
  3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
  4. -
  5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
  6. -
  7. Repeat this process \( k \) times.
  8. -
- -When you are done, you can draw a histogram of the relative frequency -of \( \widehat \theta^* \). This is your estimate of the probability -distribution \( p(t) \). Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of \( \widehat{\theta}^* \). Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of \( \widehat -\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values -\( \widehat \theta ^* \). - -

-









- -

Code example for the Bootstrap method

- -

-The following code starts with a Gaussian distribution with mean value -\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data -used in the bootstrap analysis. The bootstrap analysis returns a data -set after a given number of bootstrap operations (as many as we have -data points). This data set consists of estimated mean values for each -bootstrap operation. The histogram generated by the bootstrap method -shows that the distribution for these mean values is also a Gaussian, -centered around the mean value \( \mu=100 \) but with standard deviation -\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in -this case the same as the number of original data points). The value -of the standard deviation is what we expect from the central limit -theorem. - -

- - -

from numpy import *
-from numpy.random import randint, randn
-from time import time
-import matplotlib.mlab as mlab
-import matplotlib.pyplot as plt
-
-# Returns mean of bootstrap samples                                                                                                                                                
-def stat(data):
-    return mean(data)
-
-# Bootstrap algorithm
-def bootstrap(data, statistic, R):
-    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
-    # non-parametric bootstrap         
-    for i in range(R):
-        t[i] = statistic(data[randint(0,n,n)])
-
-    # analysis    
-    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
-    print("original           bias      std. error")
-    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
-    return t
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# bootstrap returns the data sample                                    
-t = bootstrap(x, stat, datapoints)
-# the histogram of the bootstrapped  data                                                                                                    
-n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
-
-# add a 'best fit' line  
-y = mlab.normpdf( binsboot, mean(t), std(t))
-lt = plt.plot(binsboot, y, 'r--', linewidth=1)
-plt.xlabel('Smarts')
-plt.ylabel('Probability')
-plt.axis([99.5, 100.6, 0, 3.0])
-plt.grid(True)
-
-plt.show()
-
-

-









- -

Code Example for Cross-validation and \( k \)-fold Cross-validation

- -

-The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.model_selection import KFold
-from sklearn.linear_model import Ridge
-from sklearn.model_selection import cross_val_score
-from sklearn.preprocessing import PolynomialFeatures
-
-# A seed just to ensure that the random numbers are the same for every run.
-# Useful for eventual debugging.
-np.random.seed(3155)
-
-# Generate the data.
-nsamples = 100
-x = np.random.randn(nsamples)
-y = 3*x**2 + np.random.randn(nsamples)
-
-## Cross-validation on Ridge regression using KFold only
-
-# Decide degree on polynomial to fit
-poly = PolynomialFeatures(degree = 6)
-
-# Decide which values of lambda to use
-nlambdas = 500
-lambdas = np.logspace(-3, 5, nlambdas)
-
-# Initialize a KFold instance
-k = 5
-kfold = KFold(n_splits = k)
-
-# Perform the cross-validation to estimate MSE
-scores_KFold = np.zeros((nlambdas, k))
-
-i = 0
-for lmb in lambdas:
-    ridge = Ridge(alpha = lmb)
-    j = 0
-    for train_inds, test_inds in kfold.split(x):
-        xtrain = x[train_inds]
-        ytrain = y[train_inds]
-
-        xtest = x[test_inds]
-        ytest = y[test_inds]
-
-        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
-        ridge.fit(Xtrain, ytrain[:, np.newaxis])
-
-        Xtest = poly.fit_transform(xtest[:, np.newaxis])
-        ypred = ridge.predict(Xtest)
-
-        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
-
-        j += 1
-    i += 1
-
-
-estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
-
-## Cross-validation using cross_val_score from sklearn along with KFold
-
-# kfold is an instance initialized above as:
-# kfold = KFold(n_splits = k)
-
-estimated_mse_sklearn = np.zeros(nlambdas)
-i = 0
-for lmb in lambdas:
-    ridge = Ridge(alpha = lmb)
-
-    X = poly.fit_transform(x[:, np.newaxis])
-    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
-
-    # cross_val_score return an array containing the estimated negative mse for every fold.
-    # we have to the the mean of every array in order to get an estimate of the mse of the model
-    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
-
-    i += 1
-
-## Plot and compare the slightly different ways to perform cross-validation
-
-plt.figure()
-
-plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
-plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
-
-plt.xlabel('log10(lambda)')
-plt.ylabel('mse')
-
-plt.legend()
-
-plt.show()
-
-

-









- -

The bias-variance tradeoff

- -

-We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset \( \mathcal{L} \) consisting of the data -\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). - -

-Let us assume that the true data is generated from a noisy model - -$$ -\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} -$$ - -

-where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). - -

-In our derivation of the ordinary least squares method we defined then -an approximation to the function \( f \) in terms of the parameters -\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, -that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). - -

-Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function -$$ -C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. -$$ - -

-We can rewrite this as -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2. -$$ - -

-The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error \( \boldsymbol{\epsilon} \). - -

-To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). -We use a more compact notation in terms of the expectation value -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], -$$ - -and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], -$$ - -which, using the abovementioned expectation values can be rewritten as -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, -$$ - -that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \). - -

-









- -

Example code for Bias-Variance tradeoff

-

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-
-np.random.seed(2018)
-
-n = 500
-n_boostraps = 100
-degree = 18  # A quite high value, just to show.
-noise = 0.1
-
-# Make data set.
-x = np.linspace(-1, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
-
-# Hold out some test data that is never used in training.
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-# Combine x transformation and model into one operation.
-# Not neccesary, but convenient.
-model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
-
-# The following (m x n_bootstraps) matrix holds the column vectors y_pred
-# for each bootstrap iteration.
-y_pred = np.empty((y_test.shape[0], n_boostraps))
-for i in range(n_boostraps):
-    x_, y_ = resample(x_train, y_train)
-
-    # Evaluate the new model on the same test data each time.
-    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
-# Note: Expectations and variances taken w.r.t. different training
-# data sets, hence the axis=1. Subsequent means are taken across the test data
-# set in order to obtain a total value, but before this we have error/bias/variance
-# calculated per data point in the test set.
-# Note 2: The use of keepdims=True is important in the calculation of bias as this 
-# maintains the column vector form. Dropping this yields very unexpected results.
-error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
-bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
-variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
-print('Error:', error)
-print('Bias^2:', bias)
-print('Var:', variance)
-print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
-
-plt.plot(x[::5, :], y[::5, :], label='f(x)')
-plt.scatter(x_test, y_test, label='Data points')
-plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
-plt.legend()
-plt.show()
-
-

-









- -

Understanding what happens

-

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-
-np.random.seed(2018)
-
-n = 40
-n_boostraps = 100
-maxdegree = 14
-
-
-# Make data set.
-x = np.linspace(-3, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
-error = np.zeros(maxdegree)
-bias = np.zeros(maxdegree)
-variance = np.zeros(maxdegree)
-polydegree = np.zeros(maxdegree)
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-for degree in range(maxdegree):
-    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
-    y_pred = np.empty((y_test.shape[0], n_boostraps))
-    for i in range(n_boostraps):
-        x_, y_ = resample(x_train, y_train)
-        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
-    polydegree[degree] = degree
-    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
-    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
-    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
-    print('Polynomial degree:', degree)
-    print('Error:', error[degree])
-    print('Bias^2:', bias[degree])
-    print('Var:', variance[degree])
-    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-
-plt.plot(polydegree, np.log10(error), label='Error')
-plt.plot(polydegree, bias, label='bias')
-plt.plot(polydegree, variance, label='Variance')
-plt.legend()
-plt.show()
-
-

- - -

Summing up

- -

-The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - -

-The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below \( Var(\epsilon) \), the irreducible error. - -

-What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - -

-









- -

Another Example rom Scikit-Learn's Repository

-

- - -

"""
-============================
-Underfitting vs. Overfitting
-============================
-
-This example demonstrates the problems of underfitting and overfitting and
-how we can use linear regression with polynomial features to approximate
-nonlinear functions. The plot shows the function that we want to approximate,
-which is a part of the cosine function. In addition, the samples from the
-real function and the approximations of different models are displayed. The
-models have polynomial features of different degrees. We can see that a
-linear function (polynomial with degree 1) is not sufficient to fit the
-training samples. This is called **underfitting**. A polynomial of degree 4
-approximates the true function almost perfectly. However, for higher degrees
-the model will **overfit** the training data, i.e. it learns the noise of the
-training data.
-We evaluate quantitatively **overfitting** / **underfitting** by using
-cross-validation. We calculate the mean squared error (MSE) on the validation
-set, the higher, the less likely the model generalizes correctly from the
-training data.
-"""
-
-print(__doc__)
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.pipeline import Pipeline
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.linear_model import LinearRegression
-from sklearn.model_selection import cross_val_score
-
-
-def true_fun(X):
-    return np.cos(1.5 * np.pi * X)
-
-np.random.seed(0)
-
-n_samples = 30
-degrees = [1, 4, 15]
-
-X = np.sort(np.random.rand(n_samples))
-y = true_fun(X) + np.random.randn(n_samples) * 0.1
-
-plt.figure(figsize=(14, 5))
-for i in range(len(degrees)):
-    ax = plt.subplot(1, len(degrees), i + 1)
-    plt.setp(ax, xticks=(), yticks=())
-
-    polynomial_features = PolynomialFeatures(degree=degrees[i],
-                                             include_bias=False)
-    linear_regression = LinearRegression()
-    pipeline = Pipeline([("polynomial_features", polynomial_features),
-                         ("linear_regression", linear_regression)])
-    pipeline.fit(X[:, np.newaxis], y)
-
-    # Evaluate the models using crossvalidation
-    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
-                             scoring="neg_mean_squared_error", cv=10)
-
-    X_test = np.linspace(0, 1, 100)
-    plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
-    plt.plot(X_test, true_fun(X_test), label="True function")
-    plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
-    plt.xlabel("x")
-    plt.ylabel("y")
-    plt.xlim((0, 1))
-    plt.ylim((-2, 2))
-    plt.legend(loc="best")
-    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
-        degrees[i], -scores.mean(), scores.std()))
-plt.show()
-
-

-









- -

The one-dimensional Ising model

- -

-Let us bring back the Ising model again, but now with an additional -focus on Ridge and Lasso regression as well. We repeat some of the -basic parts of the Ising model and the setup of the training and test -data. The one-dimensional Ising model with nearest neighbor -interaction, no external field and a constant coupling constant \( J \) is -given by - -$$ -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\label{_auto17} -\end{align} -$$ - -where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins in the system is determined by \( L \). For the one-dimensional system there is no phase transition. - -

-We will look at a system of \( L = 40 \) spins with a coupling constant of \( J = 1 \). To get enough training data we will generate 10000 states with their respective energies. - -

- - -

import numpy as np
-import matplotlib.pyplot as plt
-from mpl_toolkits.axes_grid1 import make_axes_locatable
-import seaborn as sns
-import scipy.linalg as scl
-from sklearn.model_selection import train_test_split
-import sklearn.linear_model as skl
-import tqdm
-sns.set(color_codes=True)
-cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
-
-L = 40
-n = int(1e4)
-
-spins = np.random.choice([-1, 1], size=(n, L))
-J = 1.0
-
-energies = np.zeros(n)
-
-for i in range(n):
-    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-
-

-A more general form for the one-dimensional Ising model is - -$$ -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\label{_auto18} -\end{align} -$$ - -

-Here we allow for interactions beyond the nearest neighbors and a more -adaptive coupling matrix. This latter expression can be formulated as -a matrix-product on the form -$$ -\begin{align} - H = X J, -\label{_auto19} -\end{align} -$$ - -

-where \( X_{jk} = s_j s_k \) and \( J \) is the matrix consisting of the -elements \( -J_{jk} \). This form of writing the energy fits perfectly -with the form utilized in linear regression, viz. -$$ -\begin{align} - \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}. -\label{_auto20} -\end{align} -$$ - -We organize the data as we did above -

- - -

X = np.zeros((n, L ** 2))
-for i in range(n):
-    X[i] = np.outer(spins[i], spins[i]).ravel()
-y = energies
-X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)
-
-X_train_own = np.concatenate(
-    (np.ones(len(X_train))[:, np.newaxis], X_train),
-    axis=1
-)
-
-X_test_own = np.concatenate(
-    (np.ones(len(X_test))[:, np.newaxis], X_test),
-    axis=1
-)
-
-

-We will do all fitting with Scikit-Learn, - -

- - -

clf = skl.LinearRegression().fit(X_train, y_train)
-
-

-When extracting the \( J \)-matrix we make sure to remove the intercept -

- - -

J_sk = clf.coef_.reshape(L, L)
-
-

-And then we plot the results -

- - -

fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_sk, **cmap_args)
-plt.title("LinearRegression from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-plt.show()
-
-

-The results perfectly with our previous discussion where we used our own code. - -

-









- -

Ridge regression

- -

-Having explored the ordinary least squares we move on to ridge -regression. In ridge regression we include a regularizer. This -involves a new cost function which leads to a new estimate for the -weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The -cost function is given by - -$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}. -\label{_auto21} -\end{align} -$$ - -

- - -

_lambda = 0.1
-clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
-J_ridge_sk = clf_ridge.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_ridge_sk, **cmap_args)
-plt.title("Ridge from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-plt.show()
-
-

-









- -

LASSO regression

- -

-In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function. - -$$ -\begin{align} - C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}. -\label{_auto22} -\end{align} -$$ - -

-Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn. - -

- - -

clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)
-J_lasso_sk = clf_lasso.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_lasso_sk, **cmap_args)
-plt.title("Lasso from Scikit-learn", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-plt.show()
-
-

-It is quite striking how LASSO breaks the symmetry of the coupling -constant as opposed to ridge and OLS. We get a sparse solution with -\( J_{j, j + 1} = -1 \). - -

-









- -

Performance as function of the regularization parameter

- -

-We see how the different models perform for a different set of values for \( \lambda \). - -

- - -

lambdas = np.logspace(-4, 5, 10)
-
-train_errors = {
-    "ols_sk": np.zeros(lambdas.size),
-    "ridge_sk": np.zeros(lambdas.size),
-    "lasso_sk": np.zeros(lambdas.size)
-}
-
-test_errors = {
-    "ols_sk": np.zeros(lambdas.size),
-    "ridge_sk": np.zeros(lambdas.size),
-    "lasso_sk": np.zeros(lambdas.size)
-}
-
-plot_counter = 1
-
-fig = plt.figure(figsize=(32, 54))
-
-for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
-    for key, method in zip(
-        ["ols_sk", "ridge_sk", "lasso_sk"],
-        [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
-    ):
-        method = method.fit(X_train, y_train)
-
-        train_errors[key][i] = method.score(X_train, y_train)
-        test_errors[key][i] = method.score(X_test, y_test)
-
-        omega = method.coef_.reshape(L, L)
-
-        plt.subplot(10, 5, plot_counter)
-        plt.imshow(omega, **cmap_args)
-        plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda))
-        plot_counter += 1
-
-plt.show()
-
-

-We see that LASSO reaches a good solution for low -values of \( \lambda \), but will "wither" when we increase \( \lambda \) too -much. Ridge is more stable over a larger range of values for -\( \lambda \), but eventually also fades away. - -

-









- -

Finding the optimal value of \( \lambda \)

- -

-To determine which value of \( \lambda \) is best we plot the accuracy of -the models when predicting the training and the testing set. We expect -the accuracy of the training set to be quite good, but if the accuracy -of the testing set is much lower this tells us that we might be -subject to an overfit model. The ideal scenario is an accuracy on the -testing set that is close to the accuracy of the training set. - -

- - -

fig = plt.figure(figsize=(20, 14))
-
-colors = {
-    "ols_sk": "r",
-    "ridge_sk": "y",
-    "lasso_sk": "c"
-}
-
-for key in train_errors:
-    plt.semilogx(
-        lambdas,
-        train_errors[key],
-        colors[key],
-        label="Train {0}".format(key),
-        linewidth=4.0
-    )
-
-for key in test_errors:
-    plt.semilogx(
-        lambdas,
-        test_errors[key],
-        colors[key] + "--",
-        label="Test {0}".format(key),
-        linewidth=4.0
-    )
-plt.legend(loc="best", fontsize=18)
-plt.xlabel(r"$\lambda$", fontsize=18)
-plt.ylabel(r"$R^2$", fontsize=18)
-plt.tick_params(labelsize=18)
-plt.show()
-
-

-From the above figure we can see that LASSO with \( \lambda = 10^{-2} \) -achieves a very good accuracy on the test set. This by far surpasses the -other models for all values of \( \lambda \). - -

-









- -

Further Exercises

- -

Exercise 1

- -

-We will 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,1)
-y = 5*x*x+0.1*np.random.randn(100,1)
-
-
    -
  1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial.
  2. -
  3. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
  4. -
  5. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  6. -
- -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -

-You can use the functionality included in scikit-learn. If you feel -for it, you can use your own program and define functions which -compute the above two functions. Discuss the meaning of these -results. Try also to vary the coefficient in front of the added -stochastic noise term and discuss the quality of the fits. - -

Exercise 2, variance of the parameters \( \beta \) in linear regression

- -

-Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as - -$$ -\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, -$$ - -with -$$ -\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, -$$ - -where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)). - -

Exercise 3

- -

-This exercise is a continuation of exercise 1. 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. You can use the code under the Regression as an example on how to use the Ridge and the Lasso 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,1)
-y = 5*x*x+0.1*np.random.randn(100,1)
-
-
    -
  1. Write your own code for the Ridge method and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 1. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
  2. -
  3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
  4. -
  5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing 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 that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions
  6. -
  7. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.
  8. -
  9. Try to implement the cross-validation as well.
  10. -
  11. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  12. -
- -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. - -

Exercise 4

- -

-We will study how -to fit polynomials to a specific two-dimensional function called -Franke's -function. This -is a function which has been widely used when testing various interpolation and fitting -algorithms. Furthermore, after having established the model and the -method, we will employ resamling techniques such as the cross-validation and/or -the bootstrap methods, in order to perform a proper assessment of our models. - -

-The Franke function, which is a weighted sum of four exponentials reads as follows -$$ -\begin{align*} -f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ -&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. -\end{align*} -$$ - -

-The function will be defined for \( x,y\in [0,1] \). Our first step will -be to perform an OLS regression analysis of this function, trying out -a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y, -x^2, y^2, xy, \dots] \). We will also include cross-validation and -bootstrap as resampling techniques. As in homeworks 1 and 2, we -can use a uniform distribution to set up the arrays of values for \( x \) -and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size. -In this case we will have two predictors and need to fit a -function (for example a polynomial) of \( x \) and \( y \). Thereafter we will -repeat much of the same procedure using the the Ridge and -Lasso regression methods, introducing thus a dependence on the bias -(penalty) \( \lambda \). - -

-The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) -

- - -

from mpl_toolkits.mplot3d import Axes3D
-import matplotlib.pyplot as plt
-from matplotlib import cm
-from matplotlib.ticker import LinearLocator, FormatStrFormatter
-import numpy as np
-from random import random, seed
-
-fig = plt.figure()
-ax = fig.gca(projection='3d')
-
-# Make data.
-x = np.arange(0, 1, 0.05)
-y = np.arange(0, 1, 0.05)
-x, y = np.meshgrid(x,y)
-
-
-def FrankeFunction(x,y):
-    term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-    term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-    term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-    term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-    return term1 + term2 + term3 + term4
-
-
-z = FrankeFunction(x, y)
-
-# Plot the surface.
-surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
-                       linewidth=0, antialiased=False)
-
-# Customize the z axis.
-ax.set_zlim(-0.10, 1.40)
-ax.zaxis.set_major_locator(LinearLocator(10))
-ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
-
-# Add a color bar which maps values to colors.
-fig.colorbar(surf, shrink=0.5, aspect=5)
-
-plt.show()
-
-

-We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where -\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform -distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition -an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). - -

-Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3 -and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -and the \( R^2 \) score function. -If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -

-Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm -and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models. - -

-Write then your own code for the Ridge method, either using matrix -inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the -previous exercise (for the same polynomials and include resampling -techniques) but now for different values of \( \lambda \). Compare and -analyze your results with those obtained with standard OLS. Study the -dependence on \( \lambda \) while also varying eventually the strength of -the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). - -

-Then perform the same studies but now with Lasso regression. Use the functionalities of -scikit-learn. Give a critical discussion of the three methods and a -judgement of which model fits the data best. - - - - -

- © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - - - - diff --git a/doc/src/Regression/Regression.idx b/doc/src/Regression/Regression.idx deleted file mode 100644 index e69de29bb..000000000 diff --git a/doc/src/Regression/Regression.ipynb b/doc/src/Regression/Regression.ipynb deleted file mode 100644 index 6db4e651c..000000000 --- a/doc/src/Regression/Regression.ipynb +++ /dev/null @@ -1,5838 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "# Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis\n", - "\n", - " \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: **Jul 22, 2019**\n", - "\n", - "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", - "\n", - "\n", - "\n", - "\n", - "## Why Linear Regression (aka Ordinary Least Squares and family)\n", - "\n", - "Fitting a continuous function with linear parameterization in terms of the parameters $\\boldsymbol{\\beta}$.\n", - "* Method of choice for fitting a continuous function!\n", - "\n", - "* Gives an excellent introduction to central Machine Learning features with **understandable pedagogical** links to other methods like **Neural Networks**, **Support Vector Machines** etc\n", - "\n", - "* Analytical expression for the fitting parameters $\\boldsymbol{\\beta}$\n", - "\n", - "* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more\n", - "\n", - "* Analytical relation with probabilistic interpretations \n", - "\n", - "* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics\n", - "\n", - "* Easy to code! And links well with classification problems and logistic regression and neural networks\n", - "\n", - "* Allows for **easy** hands-on understanding of gradient descent methods\n", - "\n", - "* and many more features\n", - "\n", - "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n", - "\n", - "\n", - "## Regression analysis, overarching aims\n", - "\n", - "Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\\boldsymbol{x} =[x_0, x_1,\\dots, x_{n-1}]^T$. \n", - "The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\boldsymbol{x}$ is called the independent variable, or the predictor variable or the explanatory variable. \n", - "\n", - "A regression model aims at finding a likelihood function $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$, that is the conditional distribution for $\\boldsymbol{y}$ with a given $\\boldsymbol{x}$. The estimation of $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$ is made using a data set with \n", - "* $n$ cases $i = 0, 1, 2, \\dots, n-1$ \n", - "\n", - "* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n", - "\n", - "* $p$ so-called explanatory (independent or predictor) variables $\\boldsymbol{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip-1}]$ with $i = 0, 1, 2, \\dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. \n", - "\n", - " The goal of the regression analysis is to extract/exploit relationship between $\\boldsymbol{y}$ and $\\boldsymbol{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.\n", - "\n", - "\n", - "\n", - "## Regression analysis, overarching aims II\n", - "\n", - "\n", - "Consider an experiment in which $p$ characteristics of $n$ samples are\n", - "measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix \n", - "$\\mathbf{X}$.\n", - "\n", - "The matrix $\\mathbf{X}$ is called the *design\n", - "matrix*. Additional information of the samples is available in the\n", - "form of $\\boldsymbol{y}$ (also as above). The variable $\\boldsymbol{y}$ is\n", - "generally referred to as the *response variable*. The aim of\n", - "regression analysis is to explain $\\boldsymbol{y}$ in terms of\n", - "$\\boldsymbol{X}$ through a functional relationship like $y_i =\n", - "f(\\mathbf{X}_{i,\\ast})$. When no prior knowledge on the form of\n", - "$f(\\cdot)$ is available, it is common to assume a linear relationship\n", - "between $\\boldsymbol{X}$ and $\\boldsymbol{y}$. This assumption gives rise to\n", - "the *linear regression model* where $\\boldsymbol{\\beta} = [\\beta_0, \\ldots,\n", - "\\beta_{p-1}]^{T}$ are the *regression parameters*. \n", - "\n", - "Linear regression gives us a set of analytical equations for the parameters $\\beta_j$.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Examples\n", - "In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n", - "consider the model we discussed for describing nuclear binding energies. \n", - "\n", - "There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.\n", - "Assuming" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms.\n", - "This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n", - "$p\\times n$ matrix $\\boldsymbol{X}$.\n", - "\n", - "Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the\n", - "so-called [credit card default data from Taiwan](https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub). The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \\times 30000$\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## General linear models\n", - "Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\\boldsymbol{y}=[y_0,y_1,\\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\\boldsymbol{x}=[x_0,x_1,\\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. \n", - "\n", - "Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y=y(x) \\rightarrow y(x_i)=\\tilde{y}_i+\\epsilon_i=\\sum_{j=0}^{n-1} \\beta_j x_i^j+\\epsilon_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\epsilon_i$ is the error in our approximation.\n", - "\n", - "\n", - "\n", - "\n", - "## Rewriting the fitting procedure as a linear algebra problem\n", - "For every set of values $y_i,x_i$ we have thus the corresponding set of equations" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "y_0&=\\beta_0+\\beta_1x_0^1+\\beta_2x_0^2+\\dots+\\beta_{n-1}x_0^{n-1}+\\epsilon_0\\\\\n", - "y_1&=\\beta_0+\\beta_1x_1^1+\\beta_2x_1^2+\\dots+\\beta_{n-1}x_1^{n-1}+\\epsilon_1\\\\\n", - "y_2&=\\beta_0+\\beta_1x_2^1+\\beta_2x_2^2+\\dots+\\beta_{n-1}x_2^{n-1}+\\epsilon_2\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{n-1}&=\\beta_0+\\beta_1x_{n-1}^1+\\beta_2x_{n-1}^2+\\dots+\\beta_{n-1}x_{n-1}^{n-1}+\\epsilon_{n-1}.\\\\\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Rewriting the fitting procedure as a linear algebra problem, more details\n", - "Defining the vectors" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta} = [\\beta_0,\\beta_1, \\beta_2,\\dots, \\beta_{n-1}]^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the design matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\n", - "\\begin{bmatrix} \n", - "1& x_{0}^1 &x_{0}^2& \\dots & \\dots &x_{0}^{n-1}\\\\\n", - "1& x_{1}^1 &x_{1}^2& \\dots & \\dots &x_{1}^{n-1}\\\\\n", - "1& x_{2}^1 &x_{2}^2& \\dots & \\dots &x_{2}^{n-1}\\\\ \n", - "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n", - "1& x_{n-1}^1 &x_{n-1}^2& \\dots & \\dots &x_{n-1}^{n-1}\\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we can rewrite our equations as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The above design matrix is called a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix).\n", - "\n", - "\n", - "\n", - "\n", - "## Generalizing the fitting procedure as a linear algebra problem\n", - "\n", - "We are obviously not limited to the above polynomial expansions. We\n", - "could replace the various powers of $x$ with elements of Fourier\n", - "series or instead of $x_i^j$ we could have $\\cos{(j x_i)}$ or $\\sin{(j\n", - "x_i)}$, or time series or other orthogonal functions. For every set\n", - "of values $y_i,x_i$ we can then generalize the equations to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n", - "y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n", - "y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_2\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_i\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!**\n", - "\n", - "\n", - "\n", - "\n", - "## Generalizing the fitting procedure as a linear algebra problem\n", - "We redefine in turn the matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\n", - "\\begin{bmatrix} \n", - "x_{00}& x_{01} &x_{02}& \\dots & \\dots &x_{0,n-1}\\\\\n", - "x_{10}& x_{11} &x_{12}& \\dots & \\dots &x_{1,n-1}\\\\\n", - "x_{20}& x_{21} &x_{22}& \\dots & \\dots &x_{2,n-1}\\\\ \n", - "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n", - "x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \\dots & \\dots &x_{n-1,n-1}\\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and without loss of generality we rewrite again our equations as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The left-hand side of this equation is kwown. Our error vector $\\boldsymbol{\\epsilon}$ and the parameter vector $\\boldsymbol{\\beta}$ are our unknow quantities. How can we obtain the optimal set of $\\beta_i$ values?\n", - "\n", - "\n", - "\n", - "\n", - "## Optimizing our parameters\n", - "We have defined the matrix $\\boldsymbol{X}$ via the equations" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n", - "y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n", - "y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_1\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_1\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As we noted above, we stayed with a system with the design matrix \n", - " $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define \n", - "our matrix as $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements.\n", - "\n", - "\n", - "\n", - "\n", - "## Our model for the nuclear binding energies\n", - "\n", - "In our [introductory notes](https://compphysics.github.io/MachineLearningMSU/doc/pub/Introduction/html/Introduction.html) we looked at the so-called [liguid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n", - "\n", - "We restate the parts of the code we are most interested in." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from IPython.display import display\n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"MassEval2016.dat\"),'r')\n", - "\n", - "\n", - "# Read the experimental data with Pandas\n", - "Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n", - " names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n", - " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n", - " header=39,\n", - " index_col=False)\n", - "\n", - "# Extrapolated values are indicated by '#' in place of the decimal place, so\n", - "# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n", - "Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n", - "Masses = Masses.dropna()\n", - "# Convert from keV to MeV.\n", - "Masses['Ebinding'] /= 1000\n", - "\n", - "# Group the DataFrame by nucleon number, A.\n", - "Masses = Masses.groupby('A')\n", - "# Find the rows of the grouped DataFrame with the maximum binding energy.\n", - "Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])\n", - "A = Masses['A']\n", - "Z = Masses['Z']\n", - "N = Masses['N']\n", - "Element = Masses['Element']\n", - "Energies = Masses['Ebinding']\n", - "\n", - "# Now we set up the design matrix X\n", - "X = np.zeros((len(A),5))\n", - "X[:,0] = 1\n", - "X[:,1] = A\n", - "X[:,2] = A**(2.0/3.0)\n", - "X[:,3] = A**(-1.0/3.0)\n", - "X[:,4] = A**(-1.0)\n", - "# Then nice printout using pandas\n", - "DesignMatrix = pd.DataFrame(X)\n", - "DesignMatrix.index = A\n", - "DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']\n", - "display(DesignMatrix)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With $\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p\\times 1}$, it means that we will hereafter write our equations for the approximation as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "throughout these lectures. \n", - "\n", - "\n", - "## Optimizing our parameters, more details\n", - "With the above we use the design matrix to define the approximation $\\boldsymbol{\\tilde{y}}$ via the unknown quantity $\\boldsymbol{\\beta}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and in order to find the optimal parameters $\\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parameterized values $\\tilde{y}_i$, namely" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or using the matrix $\\boldsymbol{X}$ and in a more compact matrix-vector notation as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}^T\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}^T\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This function is one possible way to define the so-called cost function.\n", - "\n", - "\n", - "\n", - "It is also common to define\n", - "the function $Q$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{2n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out.\n", - "\n", - "\n", - "\n", - "\n", - "## Interpretations and optimizing our parameters\n", - "\n", - "The function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. \n", - "When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y_{i}=\\langle y_i \\rangle = \\beta_0x_{i,0}+\\beta_1x_{i,1}+\\beta_2x_{i,2}+\\dots+\\beta_{n-1}x_{i,n-1}+\\epsilon_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\langle y_i \\rangle$ is the mean value. Keep in mind also that\n", - "till now we have treated $y_i$ as the exact value. Normally, the\n", - "response (dependent or outcome) variable $y_i$ the outcome of a\n", - "numerical experiment or another type of experiment and is thus only an\n", - "approximation to the true value. It is then always accompanied by an\n", - "error estimate, often limited to a statistical error estimate given by\n", - "the standard deviation discussed earlier. In the discussion here we\n", - "will treat $y_i$ as our exact value for the response variable.\n", - "\n", - "In order to find the parameters $\\beta_i$ we will then minimize the spread of $C(\\boldsymbol{\\beta})$, that is we are going to solve the problem" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In practical terms it means we will require" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)^2\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which results in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_{ij}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or in a matrix-vector form as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Interpretations and optimizing our parameters\n", - "We can rewrite" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and if the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ is invertible we have the solution" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta} =\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We note also that since our design matrix is defined as $\\boldsymbol{X}\\in\n", - "{\\mathbb{R}}^{n\\times p}$, the product $\\boldsymbol{X}^T\\boldsymbol{X} \\in\n", - "{\\mathbb{R}}^{p\\times p}$. In the above case we have that $p \\ll n$,\n", - "in our case $p=5$ meaning that we end up with inverting a small\n", - "$5\\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional\n", - "matrices to invert. The methods discussed here and for many other\n", - "supervised learning algorithms like classification with logistic\n", - "regression or support vector machines, exhibit dimensionalities which\n", - "allow for the usage of direct linear algebra methods such as **LU** decomposition or **Singular Value Decomposition** (SVD) for finding the inverse of the matrix\n", - "$\\boldsymbol{X}^T\\boldsymbol{X}$.\n", - "\n", - "\n", - "\n", - "## Interpretations and optimizing our parameters\n", - "The residuals $\\boldsymbol{\\epsilon}$ are in turn given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\epsilon} = \\boldsymbol{y}-\\boldsymbol{\\tilde{y}} = \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and with" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{\\epsilon}=\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "meaning that the solution for $\\boldsymbol{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n", - "\n", - "\n", - "\n", - "\n", - "Let us now return to our nuclear binding energies and simply code the above equations. \n", - "\n", - "## Own code for Ordinary Least Squares\n", - "\n", - "It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ we simply need to \n", - "write" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# matrix inversion to find beta\n", - "beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)\n", - "# and then make the prediction\n", - "ytilde = X @ beta" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Alternatively, you can use the least squares functionality in **Numpy** as" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n", - "ytildenp = np.dot(fit,X.T)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And finally we plot our fit with and compare with data" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "Masses['Eapprox'] = ytilde\n", - "# Generate a plot comparing the experimental with the fitted values values.\n", - "fig, ax = plt.subplots()\n", - "ax.set_xlabel(r'$A = N + Z$')\n", - "ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n", - "ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n", - " label='Ame2016')\n", - "ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n", - " label='Fit')\n", - "ax.legend()\n", - "save_fig(\"Masses2016OLS\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Adding error analysis and training set up\n", - "\n", - "We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides.\n", - "Since we are not using _Scikit-Learn here we can define our own $R2$ function as" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and we would be using it as" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "print(R2(Energies,ytilde))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can easily add our **MSE** score as" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "print(MSE(Energies,ytilde))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and finally the relative error as" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def RelativeError(y_data,y_model):\n", - " return abs((y_data-y_model)/y_data)\n", - "print(RelativeError(Energies, ytilde))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The $\\chi^2$ function\n", - "\n", - "Normally, the response (dependent or outcome) variable $y_i$ is the\n", - "outcome of a numerical experiment or another type of experiment and is\n", - "thus only an approximation to the true value. It is then always\n", - "accompanied by an error estimate, often limited to a statistical error\n", - "estimate given by the standard deviation discussed earlier. In the\n", - "discussion here we will treat $y_i$ as our exact value for the\n", - "response variable.\n", - "\n", - "Introducing the standard deviation $\\sigma_i$ for each measurement\n", - "$y_i$, we define now the $\\chi^2$ function (omitting the $1/n$ term)\n", - "as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\chi^2(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\frac{\\left(y_i-\\tilde{y}_i\\right)^2}{\\sigma_i^2}=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\frac{1}{\\boldsymbol{\\Sigma^2}}\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the matrix $\\boldsymbol{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements.\n", - "\n", - "\n", - "\n", - "## The $\\chi^2$ function\n", - "\n", - "In order to find the parameters $\\beta_i$ we will then minimize the spread of $\\chi^2(\\boldsymbol{\\beta})$ by requiring" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)^2\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which results in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}\\frac{x_{ij}}{\\sigma_i}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or in a matrix-vector form as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have defined the matrix $\\boldsymbol{A} =\\boldsymbol{X}/\\boldsymbol{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\boldsymbol{b}$ with elements $b_i = y_i/\\sigma_i$.\n", - "\n", - "\n", - "\n", - "## The $\\chi^2$ function\n", - "\n", - "We can rewrite" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{A}^T\\boldsymbol{b} = \\boldsymbol{A}^T\\boldsymbol{A}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and if the matrix $\\boldsymbol{A}^T\\boldsymbol{A}$ is invertible we have the solution" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta} =\\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1}\\boldsymbol{A}^T\\boldsymbol{b}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The $\\chi^2$ function\n", - "\n", - "If we then introduce the matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{H} = \\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\boldsymbol{H}$ are $h_{ij}$)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\beta_j = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}\\frac{y_i}{\\sigma_i}\\frac{x_{ik}}{\\sigma_i} = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}b_ia_{ik}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We state without proof the expression for the uncertainty in the parameters $\\beta_j$ as (we leave this as an exercise)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma^2(\\beta_j) = \\sum_{i=0}^{n-1}\\sigma_i^2\\left( \\frac{\\partial \\beta_j}{\\partial y_i}\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "resulting in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma^2(\\beta_j) = \\left(\\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}a_{ik}\\right)\\left(\\sum_{l=0}^{p-1}h_{jl}\\sum_{m=0}^{n-1}a_{ml}\\right) = h_{jj}!\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The $\\chi^2$ function\n", - "The first step here is to approximate the function $y$ with a first-order polynomial, that is we write" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y=y(x) \\rightarrow y(x_i) \\approx \\beta_0+\\beta_1 x_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By computing the derivatives of $\\chi^2$ with respect to $\\beta_0$ and $\\beta_1$ show that these are given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_0} = -2\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_1} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_i\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The $\\chi^2$ function\n", - "\n", - "For a linear fit (a first-order polynomial) we don't need to invert a matrix!! \n", - "Defining" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\gamma = \\sum_{i=0}^{n-1}\\frac{1}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\gamma_x = \\sum_{i=0}^{n-1}\\frac{x_{i}}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\gamma_y = \\sum_{i=0}^{n-1}\\left(\\frac{y_i}{\\sigma_i^2}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\gamma_{xx} = \\sum_{i=0}^{n-1}\\frac{x_ix_{i}}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\gamma_{xy} = \\sum_{i=0}^{n-1}\\frac{y_ix_{i}}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we obtain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\beta_0 = \\frac{\\gamma_{xx}\\gamma_y-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\beta_1 = \\frac{\\gamma_{xy}\\gamma-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This approach (different linear and non-linear regression) suffers\n", - "often from both being underdetermined and overdetermined in the\n", - "unknown coefficients $\\beta_i$. A better approach is to use the\n", - "Singular Value Decomposition (SVD) method discussed below. Or using\n", - "Lasso and Ridge regression. See below.\n", - "\n", - "\n", - "\n", - "\n", - "## Fitting an Equation of State for Dense Nuclear Matter\n", - "\n", - "Before we continue, let us introduce yet another example. We are going to fit the\n", - "nuclear equation of state using results from many-body calculations.\n", - "The equation of state we have made available here, as function of\n", - "density, has been derived using modern nucleon-nucleon potentials with\n", - "[the addition of three-body\n", - "forces](https://www.sciencedirect.com/science/article/pii/S0370157399001106). This\n", - "time the file is presented as a standard **csv** file.\n", - "\n", - "The beginning of the Python code here is similar to what you have seen before,\n", - "with the same initializations and declarations. We use also **pandas**\n", - "again, rather extensively in order to organize our data.\n", - "\n", - "The difference now is that we use **Scikit-Learn's** regression tools\n", - "instead of our own matrix inversion implementation. Furthermore, we\n", - "sneak in **Ridge** regression (to be discussed below) which includes a\n", - "hyperparameter $\\lambda$, also to be explained below.\n", - "\n", - "## The code" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "import matplotlib.pyplot as plt\n", - "import sklearn.linear_model as skl\n", - "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"EoS.csv\"),'r')\n", - "\n", - "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n", - "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", - "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", - "EoS = EoS.dropna()\n", - "Energies = EoS['Energy']\n", - "Density = EoS['Density']\n", - "# The design matrix now as function of various polytrops\n", - "X = np.zeros((len(Density),4))\n", - "X[:,3] = Density**(4.0/3.0)\n", - "X[:,2] = Density\n", - "X[:,1] = Density**(2.0/3.0)\n", - "X[:,0] = 1\n", - "\n", - "# We use now Scikit-Learn's linear regressor and ridge regressor\n", - "# OLS part\n", - "clf = skl.LinearRegression().fit(X, Energies)\n", - "ytilde = clf.predict(X)\n", - "EoS['Eols'] = ytilde\n", - "# The mean squared error \n", - "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, ytilde))\n", - "# Explained variance score: 1 is perfect prediction \n", - "print('Variance score: %.2f' % r2_score(Energies, ytilde))\n", - "# Mean absolute error \n", - "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))\n", - "print(clf.coef_, clf.intercept_)\n", - "\n", - "# The Ridge regression with a hyperparameter lambda = 0.1\n", - "_lambda = 0.1\n", - "clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)\n", - "yridge = clf_ridge.predict(X)\n", - "EoS['Eridge'] = yridge\n", - "# The mean squared error \n", - "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, yridge))\n", - "# Explained variance score: 1 is perfect prediction \n", - "print('Variance score: %.2f' % r2_score(Energies, yridge))\n", - "# Mean absolute error \n", - "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))\n", - "print(clf_ridge.coef_, clf_ridge.intercept_)\n", - "\n", - "fig, ax = plt.subplots()\n", - "ax.set_xlabel(r'$\\rho[\\mathrm{fm}^{-3}]$')\n", - "ax.set_ylabel(r'Energy per particle')\n", - "ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,\n", - " label='Theoretical data')\n", - "ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',\n", - " label='OLS')\n", - "ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',\n", - " label='Ridge $\\lambda = 0.1$')\n", - "ax.legend()\n", - "save_fig(\"EoSfitting\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The above simple polynomial in density $\\rho$ gives an excellent fit\n", - "to the data. Can you give an interpretation of the various powers of $\\rho$?\n", - "\n", - "We note also that there is a small deviation between the\n", - "standard OLS and the Ridge regression at higher densities. We discuss this in more detail\n", - "below.\n", - "\n", - "\n", - "## Splitting our Data in Training and Test data\n", - "\n", - "It is normal in essentially all Machine Learning studies to split the\n", - "data in a training set and a test set (sometimes also an additional\n", - "validation set). **Scikit-Learn** has an own function for this. There\n", - "is no explicit recipe for how much data should be included as training\n", - "data and say test data. An accepted rule of thumb is to use\n", - "approximately $2/3$ to $4/5$ of the data as training data. We will\n", - "postpone a discussion of this splitting to the end of these notes and\n", - "our discussion of the so-called **bias-variance** tradeoff. Here we\n", - "limit ourselves to repeat the above equation of state fitting example\n", - "but now splitting the data into a training set and a test set." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "infile = open(data_path(\"EoS.csv\"),'r')\n", - "\n", - "# Read the EoS data as csv file and organized into two arrays with density and energies\n", - "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", - "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", - "EoS = EoS.dropna()\n", - "Energies = EoS['Energy']\n", - "Density = EoS['Density']\n", - "# The design matrix now as function of various polytrops\n", - "X = np.zeros((len(Density),5))\n", - "X[:,0] = 1\n", - "X[:,1] = Density**(2.0/3.0)\n", - "X[:,2] = Density\n", - "X[:,3] = Density**(4.0/3.0)\n", - "X[:,4] = Density**(5.0/3.0)\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n", - "# matrix inversion to find beta\n", - "beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)\n", - "# and then make the prediction\n", - "ytilde = X_train @ beta\n", - "print(\"Training R2\")\n", - "print(R2(y_train,ytilde))\n", - "print(\"Training MSE\")\n", - "print(MSE(y_train,ytilde))\n", - "ypredict = X_test @ beta\n", - "print(\"Test R2\")\n", - "print(R2(y_test,ypredict))\n", - "print(\"Test MSE\")\n", - "print(MSE(y_test,ypredict))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The singular value decomposition\n", - "\n", - "\n", - "The examples we have looked at so far are cases where we normally can\n", - "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion as we\n", - "did both for the masses and the fitting of the equation of state,\n", - "leads to row vectors of the design matrix which are essentially\n", - "orthogonal due to the polynomial character of our model. This may\n", - "however not the be case in general and a standard matrix inversion\n", - "algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit\n", - "the coupling constant of the widely used Ising model. \n", - "There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. \n", - "\n", - "This is given by the **Singular Value Decomposition** algorithm, perhaps\n", - "the most powerful linear algebra algorithm. Let us look at a\n", - "different example where we may have problems with the standard matrix\n", - "inversion algorithm. Thereafter we dive into the math of the SVD.\n", - "\n", - "\n", - "\n", - "## The Ising model\n", - "\n", - "The one-dimensional Ising model with nearest neighbor interaction, no\n", - "external field and a constant coupling constant $J$ is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " H = -J \\sum_{k}^L s_k s_{k + 1},\n", - "\\label{_auto1} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $s_i \\in \\{-1, 1\\}$ and $s_{N + 1} = s_1$. The number of spins\n", - "in the system is determined by $L$. For the one-dimensional system\n", - "there is no phase transition.\n", - "\n", - "We will look at a system of $L = 40$ spins with a coupling constant of\n", - "$J = 1$. To get enough training data we will generate 10000 states\n", - "with their respective energies." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from mpl_toolkits.axes_grid1 import make_axes_locatable\n", - "import seaborn as sns\n", - "import scipy.linalg as scl\n", - "from sklearn.model_selection import train_test_split\n", - "import tqdm\n", - "sns.set(color_codes=True)\n", - "cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')\n", - "\n", - "L = 40\n", - "n = int(1e4)\n", - "\n", - "spins = np.random.choice([-1, 1], size=(n, L))\n", - "J = 1.0\n", - "\n", - "energies = np.zeros(n)\n", - "\n", - "for i in range(n):\n", - " energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here we use ordinary least squares\n", - "regression to predict the energy for the nearest neighbor\n", - "one-dimensional Ising model on a ring, i.e., the endpoints wrap\n", - "around. We will use linear regression to fit a value for\n", - "the coupling constant to achieve this.\n", - "\n", - "## Reformulating the problem to suit regression\n", - "\n", - "A more general form for the one-dimensional Ising model is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " H = - \\sum_j^L \\sum_k^L s_j s_k J_{jk}.\n", - "\\label{_auto2} \\tag{2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here we allow for interactions beyond the nearest neighbors and a state dependent\n", - "coupling constant. This latter expression can be formulated as\n", - "a matrix-product" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\boldsymbol{H} = \\boldsymbol{X} J,\n", - "\\label{_auto3} \\tag{3}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the\n", - "elements $-J_{jk}$. This form of writing the energy fits perfectly\n", - "with the form utilized in linear regression, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon},\n", - "\\label{_auto4} \\tag{4}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We split the data in training and test data as discussed in the previous example" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "X = np.zeros((n, L ** 2))\n", - "for i in range(n):\n", - " X[i] = np.outer(spins[i], spins[i]).ravel()\n", - "y = energies\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Linear regression\n", - "\n", - "In the ordinary least squares method we choose the cost function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " C(\\boldsymbol{X}, \\boldsymbol{\\beta})= \\frac{1}{n}\\left\\{(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})^T(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})\\right\\}.\n", - "\\label{_auto5} \\tag{5}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We then find the extremal point of $C$ by taking the derivative with respect to $\\boldsymbol{\\beta}$ as discussed above.\n", - "This yields the expression for $\\boldsymbol{\\beta}$ to be" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta} = \\frac{\\boldsymbol{X}^T \\boldsymbol{y}}{\\boldsymbol{X}^T \\boldsymbol{X}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which immediately imposes some requirements on $\\boldsymbol{X}$ as there must exist\n", - "an inverse of $\\boldsymbol{X}^T \\boldsymbol{X}$. If the expression we are modeling contains an\n", - "intercept, i.e., a constant term, we must make sure that the\n", - "first column of $\\boldsymbol{X}$ consists of $1$. We do this here" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "X_train_own = np.concatenate(\n", - " (np.ones(len(X_train))[:, np.newaxis], X_train),\n", - " axis=1\n", - ")\n", - "X_test_own = np.concatenate(\n", - " (np.ones(len(X_test))[:, np.newaxis], X_test),\n", - " axis=1\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", - " return scl.inv(x.T @ x) @ (x.T @ y)\n", - "beta = ols_inv(X_train_own, y_train)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Singular Value decomposition\n", - "\n", - "Doing the inversion directly turns out to be a bad idea since the matrix\n", - "$\\boldsymbol{X}^T\\boldsymbol{X}$ is singular. An alternative approach is to use the **singular\n", - "value decomposition**. Using the definition of the Moore-Penrose\n", - "pseudoinverse we can write the equation for $\\boldsymbol{\\beta}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta} = \\boldsymbol{X}^{+}\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the pseudoinverse of $\\boldsymbol{X}$ is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^{+} = \\frac{\\boldsymbol{X}^T}{\\boldsymbol{X}^T\\boldsymbol{X}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using singular value decomposition we can decompose the matrix $\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma} \\boldsymbol{V}^T$,\n", - "where $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal(unitary) matrices and $\\boldsymbol{\\Sigma}$ contains the singular values (more details below).\n", - "where $X^{+} = V\\Sigma^{+} U^T$. This reduces the equation for\n", - "$\\omega$ to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\boldsymbol{\\beta} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^{+} \\boldsymbol{U}^T \\boldsymbol{y}.\n", - "\\label{_auto6} \\tag{6}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Note that solving this equation by actually doing the pseudoinverse\n", - "(which is what we will do) is not a good idea as this operation scales\n", - "as $\\mathcal{O}(n^3)$, where $n$ is the number of elements in a\n", - "general matrix. Instead, doing $QR$-factorization and solving the\n", - "linear system as an equation would reduce this down to\n", - "$\\mathcal{O}(n^2)$ operations." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", - " u, s, v = scl.svd(x)\n", - " return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "beta = ols_svd(X_train_own,y_train)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "J = beta[1:].reshape(L, L)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "A way of looking at the coefficients in $J$ is to plot the matrices as images." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig = plt.figure(figsize=(20, 14))\n", - "im = plt.imshow(J, **cmap_args)\n", - "plt.title(\"OLS\", fontsize=18)\n", - "plt.xticks(fontsize=18)\n", - "plt.yticks(fontsize=18)\n", - "cb = fig.colorbar(im)\n", - "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It is interesting to note that OLS\n", - "considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as\n", - "valid matrix elements for $J$.\n", - "In our discussion below on hyperparameters and Ridge and Lasso regression we will see that\n", - "this problem can be removed, partly and only with Lasso regression. \n", - "\n", - "In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?\n", - "\n", - "\n", - "## Linear Regression Problems\n", - "\n", - "One of the typical problems we encounter with linear regression, in particular \n", - "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n", - "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n", - "may be linearly dependent, normally referred to as super-collinearity. \n", - "This means that the matrix may be rank deficient and it is basically impossible to \n", - "to model the data using linear regression. As an example, consider the matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\mathbf{X} & = \\left[\n", - "\\begin{array}{rrr}\n", - "1 & -1 & 2\n", - "\\\\\n", - "1 & 0 & 1\n", - "\\\\\n", - "1 & 2 & -1\n", - "\\\\\n", - "1 & 1 & 0\n", - "\\end{array} \\right]\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n", - "the first column is the row-wise sum of the other two columns. The rank (more correct,\n", - "the column rank) of a matrix is the dimension of the space spanned by the\n", - "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n", - "of linearly independent columns. In this particular case the matrix has rank 2.\n", - "\n", - "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n", - "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{x}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\boldsymbol{X} & = \\left[\n", - "\\begin{array}{rr}\n", - "1 & -1\n", - "\\\\\n", - "1 & -1\n", - "\\end{array} \\right].\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n", - "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n", - "\n", - "\n", - "## Fixing the singularity\n", - "\n", - "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n", - "\\label{_auto7} \\tag{7}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "has linearly dependent column vectors, we will not be able to compute the inverse\n", - "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n", - "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n", - "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n", - "the regression parameters $\\beta_i$ cannot be estimated.\n", - "\n", - "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n", - "\n", - "\n", - "\n", - "## Basic math of the SVD\n", - "\n", - "\n", - "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n", - "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n", - "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n", - "The matrix has then a set of eigenpairs" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the eigenvalues are given by the diagonal matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n", - "\n", - "Not all square matrices are diagonalizable. A matrix like the one discussed above" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\begin{bmatrix} \n", - "1& -1 \\\\\n", - "1& -1\\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n", - "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n", - "\n", - "\n", - "## The SVD, a Fantastic Algorithm\n", - "\n", - "\n", - "However, and this is the strength of the SVD algorithm, any general\n", - "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n", - "two orthogonal/unitary matrices. The [Singular Value Decompostion\n", - "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n", - "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n", - "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $n\\times n$\n", - "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n", - "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As an example, the above defective matrix can be decomposed as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n", - "The SVD exits always! \n", - "\n", - "\n", - "## Another Example\n", - "\n", - "Consider the following matrix which can be SVD decomposed as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\frac{1}{15}\\begin{bmatrix} 14 & 2\\\\ 4 & 22\\\\ 16 & 13\\end{matrix}=\\frac{1}{3}\\begin{bmatrix} 1& 2 & 2 \\\\ 2& -1 & 1\\\\ 2 & 1& -2\\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 1\\\\ 0 & 0\\end{bmatrix}\\frac{1}{5}\\begin{bmatrix} 3& 4 \\\\ 4& -3\\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This is a $3\\times 2$ matrix which is decomposed in terms of a\n", - "$3\\times 3$ matrix $\\boldsymbol{U}$, and a $2\\times 2$ matrix $\\boldsymbol{V}$. It is easy to see\n", - "that $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal (how?). \n", - "\n", - "And the SVD\n", - "decomposition (singular values) gives eigenvalues \n", - "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=2$, the\n", - "eigenvalues (singular values) are zero.\n", - "\n", - "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n", - "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n", - "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n", - "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n", - "singular values $\\sigma_i\\lg 0$ on the main diagonal and zeros filling\n", - "the rest of the matrix. There are at most $p$ singular values\n", - "assuming that $n > p$. In our regression examples for the nuclear\n", - "masses and the equation of state this is indeed the case, while for\n", - "the Ising model we have $p > n$. These are often cases that lead to\n", - "near singular or singular matrices.\n", - "\n", - "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n", - "\n", - "## Economy-size SVD\n", - "\n", - "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n", - "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n", - "irrelevant in our calculations since they are multiplied with the\n", - "zeros in $\\boldsymbol{\\Sigma}$.\n", - "\n", - "The economy-size decomposition removes extra rows or columns of zeros\n", - "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n", - "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n", - "Removing these zeros and columns can improve execution time\n", - "and reduce storage requirements without compromising the accuracy of\n", - "the decomposition.\n", - "\n", - "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n", - "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n", - "The $n=p$ case is obvious, we retain the full SVD. \n", - "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.\n", - "\n", - "## Mathematical Properties\n", - "\n", - "There are several interesting mathematical properties which will be\n", - "relevant when we are going to discuss the differences between say\n", - "ordinary least squares (OLS) and **Ridge** regression.\n", - "\n", - "We have from OLS that the parameters of the linear approximation are given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The matrix to invert can be rewritten in terms of our SVD decomposition as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using the orthogonality properties of $\\boldsymbol{U}$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T = \\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. \n", - "\n", - "This means that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "(\\boldsymbol{X}^T\\boldsymbol{X})\\boldsymbol{V} = \\boldsymbol{V}\\boldsymbol{D},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "that is the eigenvectors of $(\\boldsymbol{X}^T\\boldsymbol{X})$ are given by the columns of the right singular matrix of $\\boldsymbol{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "that is, the eigenvectors of $(\\boldsymbol{X}\\boldsymbol{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. \n", - "\n", - "Going back to our OLS equation we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We will come back to this expression when we discuss Ridge regression. \n", - "\n", - "\n", - "## Ridge and LASSO Regression\n", - "\n", - "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 \n", - "our optimization problem is" - ] - }, - { - "cell_type": "markdown", - "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", - "metadata": {}, - "source": [ - "or we can state it as" - ] - }, - { - "cell_type": "markdown", - "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", - "metadata": {}, - "source": [ - "where we have used the definition of a norm-2 vector, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "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}$. We can add a regularization parameter $\\lambda$ by\n", - "defining a new cost function to be optimized, that is" - ] - }, - { - "cell_type": "markdown", - "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", - "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. By defining" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "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,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have a new optimization equation" - ] - }, - { - "cell_type": "markdown", - "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_1\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n", - "\n", - "Here we have defined the norm-1 as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## More on Ridge Regression\n", - "\n", - "Using the matrix-vector expression for Ridge regression," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "by taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n", - "a slightly modified matrix inversion problem which for finite values\n", - "of $\\lambda$ does not suffer from singularity problems. We obtain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $t$ a finite positive number. \n", - "\n", - "We see that Ridge regression is nothing but the standard\n", - "OLS with a modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The\n", - "consequences, in particular for our discussion of the bias-variance\n", - "are rather interesting.\n", - "\n", - "Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For Ridge regression this becomes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\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", - "metadata": {}, - "source": [ - "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$. \n", - "\n", - "## Interpreting the Ridge results\n", - "\n", - "Since $\\lambda \\geq 0$, it means that compared to OLS, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n", - "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n", - "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n", - "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n", - "\\sigma_{i+1}$.\n", - "\n", - "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.\n", - "Actually, calculating the variance of $\\boldsymbol{X}\\boldsymbol{v}_j$ shows that this quantity is equal to $\\sigma_j^2/n$.\n", - "With a parameter $\\lambda$ we can thus shrink the role of specific parameters. \n", - "\n", - "\n", - "## More interpretations\n", - "\n", - "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this case the standard OLS results in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\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}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n", - "the Ridge estimator converges to zero when the hyperparameter goes to\n", - "infinity.\n", - "\n", - "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n", - "\n", - "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n", - "\n", - "## Where are we going?\n", - "\n", - "Before we proceed, we need to rethink what we have been doing. In our\n", - "eager to fit the data, we have omitted several important elements in\n", - "our regression analysis. In what follows we will\n", - "1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff\n", - "\n", - "2. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more\n", - "\n", - "This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Resampling methods\n", - "Resampling methods are an indispensable tool in modern\n", - "statistics. They involve repeatedly drawing samples from a training\n", - "set and refitting a model of interest on each sample in order to\n", - "obtain additional information about the fitted model. For example, in\n", - "order to estimate the variability of a linear regression fit, we can\n", - "repeatedly draw different samples from the training data, fit a linear\n", - "regression to each new sample, and then examine the extent to which\n", - "the resulting fits differ. Such an approach may allow us to obtain\n", - "information that would not be available from fitting the model only\n", - "once using the original training sample.\n", - "\n", - "\n", - "\n", - "## Resampling approaches can be computationally expensive\n", - "\n", - "Resampling approaches can be computationally expensive, because they\n", - "involve fitting the same statistical method multiple times using\n", - "different subsets of the training data. However, due to recent\n", - "advances in computing power, the computational requirements of\n", - "resampling methods generally are not prohibitive. In this chapter, we\n", - "discuss two of the most commonly used resampling methods,\n", - "cross-validation and the bootstrap. Both methods are important tools\n", - "in the practical application of many statistical learning\n", - "procedures. For example, cross-validation can be used to estimate the\n", - "test error associated with a given statistical learning method in\n", - "order to evaluate its performance, or to select the appropriate level\n", - "of flexibility. The process of evaluating a model’s performance is\n", - "known as model assessment, whereas the process of selecting the proper\n", - "level of flexibility for a model is known as model selection. The\n", - "bootstrap is widely used.\n", - "\n", - "\n", - "\n", - "## Why resampling methods ?\n", - "**Statistical analysis.**\n", - "\n", - "\n", - "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n", - "\n", - "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n", - "\n", - "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n", - "\n", - " \n", - "\n", - "## Statistical analysis\n", - "\n", - "* As in other experiments, many numerical experiments have two classes of errors:\n", - "\n", - " * Statistical errors\n", - "\n", - " * Systematical errors\n", - "\n", - "\n", - "* Statistical errors can be estimated using standard tools from statistics\n", - "\n", - "* Systematical errors are method specific and must be treated differently from case to case.\n", - "\n", - " \n", - "\n", - "## Statistics\n", - "The *probability distribution function (PDF)* is a function\n", - "$p(x)$ on the domain which, in the discrete case, gives us the\n", - "probability or relative frequency with which these values of $X$ occur:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x) = \\mathrm{prob}(X=x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the continuous case, the PDF does not directly depict the\n", - "actual probability. Instead we define the probability for the\n", - "stochastic variable to assume any value on an infinitesimal interval\n", - "around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us\n", - "the *density* of the probability rather than the probability\n", - "itself. The probability for a stochastic variable to assume any value\n", - "on a non-infinitesimal interval $[a,\\,b]$ is then just the integral:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{prob}(a\\leq X\\leq b) = \\int_a^b p(x)dx\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Qualitatively speaking, a stochastic variable represents the values of\n", - "numbers chosen as if by chance from some specified PDF so that the\n", - "selection of a large set of these numbers reproduces this PDF.\n", - "\n", - "\n", - "\n", - "\n", - "## Statistics, moments\n", - "A particularly useful class of special expectation values are the\n", - "*moments*. The $n$-th moment of the PDF $p$ is defined as\n", - "follows:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x^n\\rangle \\equiv \\int\\! x^n p(x)\\,dx\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The zero-th moment $\\langle 1\\rangle$ is just the normalization condition of\n", - "$p$. The first moment, $\\langle x\\rangle$, is called the *mean* of $p$\n", - "and often denoted by the letter $\\mu$:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x\\rangle = \\mu \\equiv \\int\\! x p(x)\\,dx\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Statistics, central moments\n", - "A special version of the moments is the set of *central moments*,\n", - "the n-th central moment defined as:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle (x-\\langle x \\rangle )^n\\rangle \\equiv \\int\\! (x-\\langle x\\rangle)^n p(x)\\,dx\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The zero-th and first central moments are both trivial, equal $1$ and\n", - "$0$, respectively. But the second central moment, known as the\n", - "*variance* of $p$, is of particular interest. For the stochastic\n", - "variable $X$, the variance is denoted as $\\sigma^2_X$ or $\\mathrm{var}(X)$:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\sigma^2_X\\ \\ =\\ \\ \\mathrm{var}(X) = \\langle (x-\\langle x\\rangle)^2\\rangle =\n", - "\\int\\! (x-\\langle x\\rangle)^2 p(x)\\,dx\n", - "\\label{_auto8} \\tag{8}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - " = \\int\\! \\left(x^2 - 2 x \\langle x\\rangle^{2} +\n", - " \\langle x\\rangle^2\\right)p(x)\\,dx\n", - "\\label{_auto9} \\tag{9}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - " = \\langle x^2\\rangle - 2 \\langle x\\rangle\\langle x\\rangle + \\langle x\\rangle^2\n", - "\\label{_auto10} \\tag{10}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - " = \\langle x^2\\rangle - \\langle x\\rangle^2\n", - "\\label{_auto11} \\tag{11}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The square root of the variance, $\\sigma =\\sqrt{\\langle (x-\\langle x\\rangle)^2\\rangle}$ is called the *standard deviation* of $p$. It is clearly just the RMS (root-mean-square)\n", - "value of the deviation of the PDF from its mean value, interpreted\n", - "qualitatively as the *spread* of $p$ around its mean.\n", - "\n", - "\n", - "\n", - "## Statistics, covariance\n", - "Another important quantity is the so called covariance, a variant of\n", - "the above defined variance. Consider again the set $\\{X_i\\}$ of $n$\n", - "stochastic variables (not necessarily uncorrelated) with the\n", - "multivariate PDF $P(x_1,\\dots,x_n)$. The *covariance* of two\n", - "of the stochastic variables, $X_i$ and $X_j$, is defined as follows:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{cov}(X_i,\\,X_j) \\equiv \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n", - "\\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=\n", - "\\int\\!\\cdots\\!\\int\\!(x_i-\\langle x_i \\rangle)(x_j-\\langle x_j \\rangle)\\,\n", - "P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n\n", - "\\label{eq:def_covariance} \\tag{12}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x_i\\rangle =\n", - "\\int\\!\\cdots\\!\\int\\!x_i\\,P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Statistics, more covariance\n", - "If we consider the above covariance as a matrix $C_{ij}=\\mathrm{cov}(X_i,\\,X_j)$, then the diagonal elements are just the familiar\n", - "variances, $C_{ii} = \\mathrm{cov}(X_i,\\,X_i) = \\mathrm{var}(X_i)$. It turns out that\n", - "all the off-diagonal elements are zero if the stochastic variables are\n", - "uncorrelated. This is easy to show, keeping in mind the linearity of\n", - "the expectation value. Consider the stochastic variables $X_i$ and\n", - "$X_j$, ($i\\neq j$):" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathrm{cov}(X_i,\\,X_j) = \\langle(x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n", - "\\label{_auto12} \\tag{13}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=\\langle x_i x_j - x_i\\langle x_j\\rangle - \\langle x_i\\rangle x_j + \\langle x_i\\rangle\\langle x_j\\rangle\\rangle \n", - "\\label{_auto13} \\tag{14}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=\\langle x_i x_j\\rangle - \\langle x_i\\langle x_j\\rangle\\rangle - \\langle \\langle x_i\\rangle x_j\\rangle +\n", - "\\langle \\langle x_i\\rangle\\langle x_j\\rangle\\rangle\n", - "\\label{_auto14} \\tag{15}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle +\n", - "\\langle x_i\\rangle\\langle x_j\\rangle\n", - "\\label{_auto15} \\tag{16}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle\n", - "\\label{_auto16} \\tag{17}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Statistics, independent variables\n", - "If $X_i$ and $X_j$ are independent, we get \n", - "$\\langle x_i x_j\\rangle =\\langle x_i\\rangle\\langle x_j\\rangle$, resulting in $\\mathrm{cov}(X_i, X_j) = 0\\ \\ (i\\neq j)$.\n", - "\n", - "Also useful for us is the covariance of linear combinations of\n", - "stochastic variables. Let $\\{X_i\\}$ and $\\{Y_i\\}$ be two sets of\n", - "stochastic variables. Let also $\\{a_i\\}$ and $\\{b_i\\}$ be two sets of\n", - "scalars. Consider the linear combination:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "U = \\sum_i a_i X_i \\qquad V = \\sum_j b_j Y_j\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By the linearity of the expectation value" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{cov}(U, V) = \\sum_{i,j}a_i b_j \\mathrm{cov}(X_i, Y_j)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Statistics, more variance\n", - "Now, since the variance is just $\\mathrm{var}(X_i) = \\mathrm{cov}(X_i, X_i)$, we get\n", - "the variance of the linear combination $U = \\sum_i a_i X_i$:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathrm{var}(U) = \\sum_{i,j}a_i a_j \\mathrm{cov}(X_i, X_j)\n", - "\\label{eq:variance_linear_combination} \\tag{18}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And in the special case when the stochastic variables are\n", - "uncorrelated, the off-diagonal elements of the covariance are as we\n", - "know zero, resulting in:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "1\n", - "1\n", - "3\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{var}(\\sum_i a_i X_i) = \\sum_i a_i^2 \\mathrm{var}(X_i)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which will become very useful in our study of the error in the mean\n", - "value of a set of measurements.\n", - "\n", - "\n", - "\n", - "## Statistics and stochastic processes\n", - "A *stochastic process* is a process that produces sequentially a\n", - "chain of values:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\{x_1, x_2,\\dots\\,x_k,\\dots\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We will call these\n", - "values our *measurements* and the entire set as our measured\n", - "*sample*. The action of measuring all the elements of a sample\n", - "we will call a stochastic *experiment* since, operationally,\n", - "they are often associated with results of empirical observation of\n", - "some physical or mathematical phenomena; precisely an experiment. We\n", - "assume that these values are distributed according to some \n", - "PDF $p_X^{\\phantom X}(x)$, where $X$ is just the formal symbol for the\n", - "stochastic variable whose PDF is $p_X^{\\phantom X}(x)$. Instead of\n", - "trying to determine the full distribution $p$ we are often only\n", - "interested in finding the few lowest moments, like the mean\n", - "$\\mu_X^{\\phantom X}$ and the variance $\\sigma_X^{\\phantom X}$.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Statistics and sample variables\n", - "In practical situations a sample is always of finite size. Let that\n", - "size be $n$. The expectation value of a sample, the *sample mean*, is then defined as follows:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\bar{x}_n \\equiv \\frac{1}{n}\\sum_{k=1}^n x_k\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The *sample variance* is:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{var}(x) \\equiv \\frac{1}{n}\\sum_{k=1}^n (x_k - \\bar{x}_n)^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "its square root being the *standard deviation of the sample*. The\n", - "*sample covariance* is:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{cov}(x)\\equiv\\frac{1}{n}\\sum_{kl}(x_k - \\bar{x}_n)(x_l - \\bar{x}_n)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Statistics, sample variance and covariance\n", - "Note that the sample variance is the sample covariance without the\n", - "cross terms. In a similar manner as the covariance in Eq. ([12](#eq:def_covariance)) is a measure of the correlation between\n", - "two stochastic variables, the above defined sample covariance is a\n", - "measure of the sequential correlation between succeeding measurements\n", - "of a sample.\n", - "\n", - "These quantities, being known experimental values, differ\n", - "significantly from and must not be confused with the similarly named\n", - "quantities for stochastic variables, mean $\\mu_X$, variance $\\mathrm{var}(X)$\n", - "and covariance $\\mathrm{cov}(X,Y)$.\n", - "\n", - "\n", - "\n", - "## Statistics, law of large numbers\n", - "The law of large numbers\n", - "states that as the size of our sample grows to infinity, the sample\n", - "mean approaches the true mean $\\mu_X^{\\phantom X}$ of the chosen PDF:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\lim_{n\\to\\infty}\\bar{x}_n = \\mu_X^{\\phantom X}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The sample mean $\\bar{x}_n$ works therefore as an estimate of the true\n", - "mean $\\mu_X^{\\phantom X}$.\n", - "\n", - "What we need to find out is how good an approximation $\\bar{x}_n$ is to\n", - "$\\mu_X^{\\phantom X}$. In any stochastic measurement, an estimated\n", - "mean is of no use to us without a measure of its error. A quantity\n", - "that tells us how well we can reproduce it in another experiment. We\n", - "are therefore interested in the PDF of the sample mean itself. Its\n", - "standard deviation will be a measure of the spread of sample means,\n", - "and we will simply call it the *error* of the sample mean, or\n", - "just sample error, and denote it by $\\mathrm{err}_X^{\\phantom X}$. In\n", - "practice, we will only be able to produce an *estimate* of the\n", - "sample error since the exact value would require the knowledge of the\n", - "true PDFs behind, which we usually do not have.\n", - "\n", - "\n", - "\n", - "\n", - "## Statistics, more on sample error\n", - "Let us first take a look at what happens to the sample error as the\n", - "size of the sample grows. In a sample, each of the measurements $x_i$\n", - "can be associated with its own stochastic variable $X_i$. The\n", - "stochastic variable $\\overline X_n$ for the sample mean $\\bar{x}_n$ is\n", - "then just a linear combination, already familiar to us:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\overline X_n = \\frac{1}{n}\\sum_{i=1}^n X_i\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "All the coefficients are just equal $1/n$. The PDF of $\\overline X_n$,\n", - "denoted by $p_{\\overline X_n}(x)$ is the desired PDF of the sample\n", - "means.\n", - "\n", - "\n", - "\n", - "## Statistics\n", - "The probability density of obtaining a sample mean $\\bar x_n$\n", - "is the product of probabilities of obtaining arbitrary values $x_1,\n", - "x_2,\\dots,x_n$ with the constraint that the mean of the set $\\{x_i\\}$\n", - "is $\\bar x_n$:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p_{\\overline X_n}(x) = \\int p_X^{\\phantom X}(x_1)\\cdots\n", - "\\int p_X^{\\phantom X}(x_n)\\ \n", - "\\delta\\!\\left(x - \\frac{x_1+x_2+\\dots+x_n}{n}\\right)dx_n \\cdots dx_1\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And in particular we are interested in its variance $\\mathrm{var}(\\overline X_n)$.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Statistics, central limit theorem\n", - "It is generally not possible to express $p_{\\overline X_n}(x)$ in a\n", - "closed form given an arbitrary PDF $p_X^{\\phantom X}$ and a number\n", - "$n$. But for the limit $n\\to\\infty$ it is possible to make an\n", - "approximation. The very important result is called *the central limit theorem*. It tells us that as $n$ goes to infinity,\n", - "$p_{\\overline X_n}(x)$ approaches a Gaussian distribution whose mean\n", - "and variance equal the true mean and variance, $\\mu_{X}^{\\phantom X}$\n", - "and $\\sigma_{X}^{2}$, respectively:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\lim_{n\\to\\infty} p_{\\overline X_n}(x) =\n", - "\\left(\\frac{n}{2\\pi\\mathrm{var}(X)}\\right)^{1/2}\n", - "e^{-\\frac{n(x-\\bar x_n)^2}{2\\mathrm{var}(X)}}\n", - "\\label{eq:central_limit_gaussian} \\tag{19}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Statistics, more technicalities\n", - "The desired variance\n", - "$\\mathrm{var}(\\overline X_n)$, i.e. the sample error squared\n", - "$\\mathrm{err}_X^2$, is given by:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathrm{err}_X^2 = \\mathrm{var}(\\overline X_n) = \\frac{1}{n^2}\n", - "\\sum_{ij} \\mathrm{cov}(X_i, X_j)\n", - "\\label{eq:error_exact} \\tag{20}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see now that in order to calculate the exact error of the sample\n", - "with the above expression, we would need the true means\n", - "$\\mu_{X_i}^{\\phantom X}$ of the stochastic variables $X_i$. To\n", - "calculate these requires that we know the true multivariate PDF of all\n", - "the $X_i$. But this PDF is unknown to us, we have only got the measurements of\n", - "one sample. The best we can do is to let the sample itself be an\n", - "estimate of the PDF of each of the $X_i$, estimating all properties of\n", - "$X_i$ through the measurements of the sample.\n", - "\n", - "\n", - "\n", - "\n", - "## Statistics\n", - "Our estimate of $\\mu_{X_i}^{\\phantom X}$ is then the sample mean $\\bar x$\n", - "itself, in accordance with the the central limit theorem:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu_{X_i}^{\\phantom X} = \\langle x_i\\rangle \\approx \\frac{1}{n}\\sum_{k=1}^n x_k = \\bar x\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using $\\bar x$ in place of $\\mu_{X_i}^{\\phantom X}$ we can give an\n", - "*estimate* of the covariance in Eq. ([20](#eq:error_exact))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{cov}(X_i, X_j) = \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n", - "\\approx\\langle (x_i - \\bar x)(x_j - \\bar{x})\\rangle,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "resulting in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{1}{n} \\sum_{l}^n \\left(\\frac{1}{n}\\sum_{k}^n (x_k -\\bar x_n)(x_l - \\bar x_n)\\right)=\\frac{1}{n}\\frac{1}{n} \\sum_{kl} (x_k -\\bar x_n)(x_l - \\bar x_n)=\\frac{1}{n}\\mathrm{cov}(x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Statistics and sample variance\n", - "By the same procedure we can use the sample variance as an\n", - "estimate of the variance of any of the stochastic variables $X_i$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{var}(X_i)=\\langle x_i - \\langle x_i\\rangle\\rangle \\approx \\langle x_i - \\bar x_n\\rangle\\nonumber,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is approximated as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathrm{var}(X_i)\\approx \\frac{1}{n}\\sum_{k=1}^n (x_k - \\bar x_n)=\\mathrm{var}(x)\n", - "\\label{eq:var_estimate_i_think} \\tag{21}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now we can calculate an estimate of the error\n", - "$\\mathrm{err}_X^{\\phantom X}$ of the sample mean $\\bar x_n$:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{err}_X^2\n", - "=\\frac{1}{n^2}\\sum_{ij} \\mathrm{cov}(X_i, X_j) \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\approx\\frac{1}{n^2}\\sum_{ij}\\frac{1}{n}\\mathrm{cov}(x) =\\frac{1}{n^2}n^2\\frac{1}{n}\\mathrm{cov}(x)\\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=\\frac{1}{n}\\mathrm{cov}(x)\n", - "\\label{eq:error_estimate} \\tag{22}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is nothing but the sample covariance divided by the number of\n", - "measurements in the sample.\n", - "\n", - "\n", - "\n", - "## Statistics, uncorrelated results\n", - "\n", - "In the special case that the measurements of the sample are\n", - "uncorrelated (equivalently the stochastic variables $X_i$ are\n", - "uncorrelated) we have that the off-diagonal elements of the covariance\n", - "are zero. This gives the following estimate of the sample error:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{err}_X^2=\\frac{1}{n^2}\\sum_{ij} \\mathrm{cov}(X_i, X_j) =\n", - "\\frac{1}{n^2} \\sum_i \\mathrm{var}(X_i),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "resulting in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathrm{err}_X^2\\approx \\frac{1}{n^2} \\sum_i \\mathrm{var}(x)= \\frac{1}{n}\\mathrm{var}(x)\n", - "\\label{eq:error_estimate_uncorrel} \\tag{23}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where in the second step we have used Eq. ([21](#eq:var_estimate_i_think)).\n", - "The error of the sample is then just its standard deviation divided by\n", - "the square root of the number of measurements the sample contains.\n", - "This is a very useful formula which is easy to compute. It acts as a\n", - "first approximation to the error, but in numerical experiments, we\n", - "cannot overlook the always present correlations.\n", - "\n", - "\n", - "\n", - "## Statistics, computations\n", - "For computational purposes one usually splits up the estimate of\n", - "$\\mathrm{err}_X^2$, given by Eq. ([22](#eq:error_estimate)), into two\n", - "parts" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{err}_X^2 = \\frac{1}{n}\\mathrm{var}(x) + \\frac{1}{n}(\\mathrm{cov}(x)-\\mathrm{var}(x)),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which equals" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\frac{1}{n^2}\\sum_{k=1}^n (x_k - \\bar x_n)^2 +\\frac{2}{n^2}\\sum_{k\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=\\frac{\\tau}{n}\\cdot\\mathrm{var}(x)\n", - "\\label{eq:error_estimate_corr_time} \\tag{25}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and we see that $\\mathrm{err}_X$ can be expressed in terms the\n", - "uncorrelated sample variance times a correction factor $\\tau$ which\n", - "accounts for the correlation between measurements. We call this\n", - "correction factor the *autocorrelation time*:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\tau = 1+2\\sum_{d=1}^{n-1}\\kappa_d\n", - "\\label{eq:autocorrelation_time} \\tag{26}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Statistics, effective number of correlations\n", - "For a correlation free experiment, $\\tau$\n", - "equals 1. From the point of view of\n", - "eq. ([25](#eq:error_estimate_corr_time)) we can interpret a sequential\n", - "correlation as an effective reduction of the number of measurements by\n", - "a factor $\\tau$. The effective number of measurements becomes:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "n_\\mathrm{eff} = \\frac{n}{\\tau}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To neglect the autocorrelation time $\\tau$ will always cause our\n", - "simple uncorrelated estimate of $\\mathrm{err}_X^2\\approx \\mathrm{var}(x)/n$ to\n", - "be less than the true sample error. The estimate of the error will be\n", - "too *good*. On the other hand, the calculation of the full\n", - "autocorrelation time poses an efficiency problem if the set of\n", - "measurements is very large.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Linking the regression analysis with a statistical interpretation\n", - "\n", - "Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. \n", - "The\n", - "advantage of doing linear regression is that we actually end up with\n", - "analytical expressions for several statistical quantities. \n", - "Standard least squares and Ridge regression allow us to\n", - "derive quantities like the variance and other expectation values in a\n", - "rather straightforward way.\n", - "\n", - "\n", - "It is assumed that $\\varepsilon_i\n", - "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n", - "independent, i.e.:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*} \n", - "\\mbox{Cov}(\\varepsilon_{i_1},\n", - "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n", - "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The randomness of $\\varepsilon_i$ implies that\n", - "$\\mathbf{y}_i$ is also a random variable. In particular,\n", - "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n", - "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n", - "non-random scalar. To specify the parameters of the distribution of\n", - "$\\mathbf{y}_i$ we need to calculate its first two moments. \n", - "\n", - "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n", - "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n", - "row number $i$ and perform a sum over all values $p$.\n", - "\n", - "\n", - "## Assumptions made\n", - "\n", - "The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off)\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", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We approximate this function with our model from the solution of the linear regression equations, that is our\n", - "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Expectation value and variance\n", - "\n", - "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*} \n", - "\\mathbb{E}(y_i) & =\n", - "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n", - "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "while\n", - "its variance is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n", - "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n", - "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n", - "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n", - "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n", - "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n", - "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n", - "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n", - "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n", - "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n", - "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n", - "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD). \n", - "\n", - "## Expectation value and variance for $\\boldsymbol{\\beta}$\n", - "\n", - "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we can evaluate the expectation value" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}(\\boldsymbol{\\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}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This means that the estimator of the regression parameters is unbiased.\n", - "\n", - "We can also calculate the variance\n", - "\n", - "The variance of $\\boldsymbol{\\beta}$ is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{eqnarray*}\n", - "\\mbox{Var}(\\boldsymbol{\\beta}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n", - "\\\\\n", - "& = & \\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} \\}\n", - "\\\\\n", - "% & = & \\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}\n", - "% \\\\\n", - "% & = & \\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}\n", - "% \\\\\n", - "& = & (\\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}\n", - "\\\\\n", - "& = & (\\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}\n", - "% \\\\\n", - "% & = & (\\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}\n", - "% \\\\\n", - "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n", - "\\\\\n", - "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n", - "\\end{eqnarray*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have used that $\\mathbb{E} (\\mathbf{Y} \\mathbf{Y}^{T}) =\n", - "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n", - "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n", - "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n", - "variance of the estimate of the $j$-th regression coefficient:\n", - "$\\hat{\\sigma}^2 (\\hat{\\beta}_j ) = \\hat{\\sigma}^2 \\sqrt{\n", - "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n", - "construct a confidence interval for the estimates.\n", - "\n", - "\n", - "In a similar way, we cna obtain analytical expressions for say the\n", - "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n", - "when we employ Ridge regression, and thereby a confidence interval. \n", - "\n", - "It is rather straightforward to show that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\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}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see clearly that \n", - "$\\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.\n", - "\n", - "We can also compute the variance as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\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},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "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. \n", - "\n", - "With this, we can compute the difference" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\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}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The difference is non-negative definite since each component of the\n", - "matrix product is non-negative definite. \n", - "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. \n", - "\n", - "\n", - "## Cross-validation\n", - "\n", - "Instead of choosing the penalty parameter to balance model fit with\n", - "model complexity, cross-validation requires it (i.e. the penalty\n", - "parameter) to yield a model with good prediction\n", - "performance. Commonly, this performance is evaluated on novel\n", - "data. Novel data need not be easy to come by and one has to make do\n", - "with the data at hand.\n", - "\n", - "The setting of **original** and novel data is\n", - "then mimicked by sample splitting: the data set is divided into two\n", - "(groups of samples). One of these two data sets, called the \n", - "*training set*, plays the role of **original** data on which the model is\n", - "built. The second of these data sets, called the *test set*, plays the\n", - "role of the **novel** data and is used to evaluate the prediction\n", - "performance (often operationalized as the log-likelihood or the\n", - "prediction error or its square or the R2 score) of the model built on the training data set. This\n", - "procedure (model building and prediction evaluation on training and\n", - "test set, respectively) is done for a collection of possible penalty\n", - "parameter choices. The penalty parameter that yields the model with\n", - "the best prediction performance is to be preferred. The thus obtained\n", - "performance evaluation depends on the actual split of the data set. To\n", - "remove this dependence the data set is split many times into a\n", - "training and test set. For each split the model parameters are\n", - "estimated for all choices of $\\lambda$ using the training data and\n", - "estimated parameters are evaluated on the corresponding test set. The\n", - "penalty parameter that on average over the test sets performs best (in\n", - "some sense) is then selected.\n", - "\n", - "\n", - "## Computationally expensive\n", - "\n", - "The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks:\n", - "\n", - "* The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set.\n", - "\n", - "* In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set.\n", - "\n", - "\n", - "## Various steps in cross-validation\n", - "\n", - "When the repetitive splitting of the data set is done randomly,\n", - "samples may accidently end up in a fast majority of the splits in\n", - "either training or test set. Such samples may have an unbalanced\n", - "influence on either model building or prediction evaluation. To avoid\n", - "this $k$-fold cross-validation structures the data splitting. The\n", - "samples are divided into $k$ more or less equally sized exhaustive and\n", - "mutually exclusive subsets. In turn (at each split) one of these\n", - "subsets plays the role of the test set while the union of the\n", - "remaining subsets constitutes the training set. Such a splitting\n", - "warrants a balanced representation of each sample in both training and\n", - "test set over the splits. Still the division into the $k$ subsets\n", - "involves a degree of randomness. This may be fully excluded when\n", - "choosing $k=n$. This particular case is referred to as leave-one-out\n", - "cross-validation (LOOCV). \n", - "\n", - "\n", - "## How to set up the cross-validation for Ridge and/or Lasso\n", - "\n", - "* Define a range of interest for the penalty parameter.\n", - "\n", - "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n", - "\n", - "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n", - "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n", - "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n", - "\n", - "* Repeat the first three steps such that each sample plays the role of the test set once.\n", - "\n", - "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the *cross-validated log-likelihood*. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions.\n", - "\n", - "## Resampling methods: Jackknife and Bootstrap\n", - "\n", - "Two famous\n", - "resampling methods are the **independent bootstrap** and **the jackknife**. \n", - "\n", - "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n", - "popular prior to the independent bootstrap. And as the popularity of\n", - "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n", - "\n", - "The Jackknife and independent bootstrap work for\n", - "independent, identically distributed random variables.\n", - "If these conditions are not\n", - "satisfied, the methods will fail. Yet, it should be said that if the data are\n", - "independent, identically distributed, and we only want to estimate the\n", - "variance of $\\overline{X}$ (which often is the case), then there is no\n", - "need for bootstrapping. \n", - "\n", - "## Resampling methods: Jackknife\n", - "\n", - "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n", - "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n", - "Let $\\boldsymbol{x}_i$ denote the vector" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n", - "number $i$ is left out. Using this notation, define\n", - "$\\widehat{\\theta}_i$ to be the estimator\n", - "$\\widehat{\\theta}$ computed using $\\vec{X}_i$. \n", - "\n", - "\n", - "## Jackknife code example" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from numpy import *\n", - "from numpy.random import randint, randn\n", - "from time import time\n", - "\n", - "def jackknife(data, stat):\n", - " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n", - " ## 'jackknifing' by leaving out an observation for each i \n", - " for i in range(n):\n", - " t[i] = stat(delete(data,i) )\n", - "\n", - " # analysis \n", - " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n", - " print(\"original bias std. error\")\n", - " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n", - "\n", - " return t\n", - "\n", - "\n", - "# Returns mean of data samples \n", - "def stat(data):\n", - " return mean(data)\n", - "\n", - "\n", - "mu, sigma = 100, 15\n", - "datapoints = 10000\n", - "x = mu + sigma*random.randn(datapoints)\n", - "# jackknife returns the data sample \n", - "t = jackknife(x, stat)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Resampling methods: Bootstrap\n", - "Bootstrapping is a nonparametric approach to statistical inference\n", - "that substitutes computation for more traditional distributional\n", - "assumptions and asymptotic results. Bootstrapping offers a number of\n", - "advantages: \n", - "1. The bootstrap is quite general, although there are some cases in which it fails. \n", - "\n", - "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n", - "\n", - "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n", - "\n", - "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n", - "\n", - "\n", - "\n", - "\n", - "## Resampling methods: Bootstrap background\n", - "\n", - "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n", - "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n", - "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n", - "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n", - "$\\widehat{\\theta}$. You can think of this as using a histogram\n", - "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n", - "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n", - "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n", - "estimators. \n", - "\n", - "\n", - "## Resampling methods: More Bootstrap background\n", - "\n", - "In the case that $\\widehat{\\theta}$ has\n", - "more than one component, and the components are independent, we use the\n", - "same estimator on each component separately. If the probability\n", - "density function of $X_i$, $p(x)$, had been known, then it would have\n", - "been straight forward to do this by: \n", - "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n", - "\n", - "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n", - "\n", - "By repeated use of (1) and (2), many\n", - "estimates of $\\widehat{\\theta}$ could have been obtained. The\n", - "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n", - "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n", - "\n", - "## Resampling methods: Bootstrap approach\n", - "\n", - "But\n", - "unless there is enough information available about the process that\n", - "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n", - "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n", - "question: What if we replace $p(x)$ by the relative frequency\n", - "of the observation $X_i$; if we draw observations in accordance with\n", - "the relative frequency of the observations, will we obtain the same\n", - "result in some asymptotic sense? The answer is yes.\n", - "\n", - "\n", - "Instead of generating the histogram for the relative\n", - "frequency of the observation $X_i$, just draw the values\n", - "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n", - "$\\boldsymbol{X}$. \n", - "\n", - "## Resampling methods: Bootstrap steps\n", - "\n", - "The independent bootstrap works like this: \n", - "\n", - "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n", - "\n", - "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n", - "\n", - "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n", - "\n", - "4. Repeat this process $k$ times. \n", - "\n", - "When you are done, you can draw a histogram of the relative frequency\n", - "of $\\widehat \\theta^*$. This is your estimate of the probability\n", - "distribution $p(t)$. Using this probability distribution you can\n", - "estimate any statistics thereof. In principle you never draw the\n", - "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n", - "you use the estimators corresponding to the statistic of interest. For\n", - "example, if you are interested in estimating the variance of $\\widehat\n", - "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n", - "$\\widehat \\theta ^*$.\n", - "\n", - "\n", - "## Code example for the Bootstrap method\n", - "\n", - "The following code starts with a Gaussian distribution with mean value\n", - "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n", - "used in the bootstrap analysis. The bootstrap analysis returns a data\n", - "set after a given number of bootstrap operations (as many as we have\n", - "data points). This data set consists of estimated mean values for each\n", - "bootstrap operation. The histogram generated by the bootstrap method\n", - "shows that the distribution for these mean values is also a Gaussian,\n", - "centered around the mean value $\\mu=100$ but with standard deviation\n", - "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n", - "this case the same as the number of original data points). The value\n", - "of the standard deviation is what we expect from the central limit\n", - "theorem." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from numpy import *\n", - "from numpy.random import randint, randn\n", - "from time import time\n", - "import matplotlib.mlab as mlab\n", - "import matplotlib.pyplot as plt\n", - "\n", - "# Returns mean of bootstrap samples \n", - "def stat(data):\n", - " return mean(data)\n", - "\n", - "# Bootstrap algorithm\n", - "def bootstrap(data, statistic, R):\n", - " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n", - " # non-parametric bootstrap \n", - " for i in range(R):\n", - " t[i] = statistic(data[randint(0,n,n)])\n", - "\n", - " # analysis \n", - " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n", - " print(\"original bias std. error\")\n", - " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n", - " return t\n", - "\n", - "\n", - "mu, sigma = 100, 15\n", - "datapoints = 10000\n", - "x = mu + sigma*random.randn(datapoints)\n", - "# bootstrap returns the data sample \n", - "t = bootstrap(x, stat, datapoints)\n", - "# the histogram of the bootstrapped data \n", - "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n", - "\n", - "# add a 'best fit' line \n", - "y = mlab.normpdf( binsboot, mean(t), std(t))\n", - "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n", - "plt.xlabel('Smarts')\n", - "plt.ylabel('Probability')\n", - "plt.axis([99.5, 100.6, 0, 3.0])\n", - "plt.grid(True)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Code Example for Cross-validation and $k$-fold Cross-validation\n", - "\n", - "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import KFold\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import cross_val_score\n", - "from sklearn.preprocessing import PolynomialFeatures\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", - "# Generate the data.\n", - "nsamples = 100\n", - "x = np.random.randn(nsamples)\n", - "y = 3*x**2 + np.random.randn(nsamples)\n", - "\n", - "## Cross-validation on Ridge regression using KFold only\n", - "\n", - "# Decide degree on polynomial to fit\n", - "poly = PolynomialFeatures(degree = 6)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 500\n", - "lambdas = np.logspace(-3, 5, nlambdas)\n", - "\n", - "# Initialize a KFold instance\n", - "k = 5\n", - "kfold = KFold(n_splits = k)\n", - "\n", - "# Perform the cross-validation to estimate MSE\n", - "scores_KFold = np.zeros((nlambdas, k))\n", - "\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - " j = 0\n", - " for train_inds, test_inds in kfold.split(x):\n", - " xtrain = x[train_inds]\n", - " ytrain = y[train_inds]\n", - "\n", - " xtest = x[test_inds]\n", - " ytest = y[test_inds]\n", - "\n", - " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n", - " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n", - "\n", - " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n", - " ypred = ridge.predict(Xtest)\n", - "\n", - " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n", - "\n", - " j += 1\n", - " i += 1\n", - "\n", - "\n", - "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n", - "\n", - "## Cross-validation using cross_val_score from sklearn along with KFold\n", - "\n", - "# kfold is an instance initialized above as:\n", - "# kfold = KFold(n_splits = k)\n", - "\n", - "estimated_mse_sklearn = np.zeros(nlambdas)\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - "\n", - " X = poly.fit_transform(x[:, np.newaxis])\n", - " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n", - "\n", - " # cross_val_score return an array containing the estimated negative mse for every fold.\n", - " # we have to the the mean of every array in order to get an estimate of the mse of the model\n", - " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", - "\n", - " i += 1\n", - "\n", - "## Plot and compare the slightly different ways to perform cross-validation\n", - "\n", - "plt.figure()\n", - "\n", - "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", - "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n", - "\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('mse')\n", - "\n", - "plt.legend()\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The bias-variance tradeoff\n", - "\n", - "\n", - "We will discuss the bias-variance tradeoff in the context of\n", - "continuous predictions such as regression. However, many of the\n", - "intuitions and ideas discussed here also carry over to classification\n", - "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n", - "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n", - "\n", - "Let us assume that the true data is generated from a noisy model" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n", - "\n", - "In our derivation of the ordinary least squares method we defined then\n", - "an approximation to the function $f$ in terms of the parameters\n", - "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n", - "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n", - "\n", - "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can rewrite this as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The three terms represent the square of the bias of the learning\n", - "method, which can be thought of as the error caused by the simplifying\n", - "assumptions built into the method. The second term represents the\n", - "variance of the chosen model and finally the last terms is variance of\n", - "the error $\\boldsymbol{\\epsilon}$.\n", - "\n", - "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n", - "We use a more compact notation in terms of the expectation value" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which, using the abovementioned expectation values can be rewritten as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Example code for Bias-Variance tradeoff" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "\n", - "np.random.seed(2018)\n", - "\n", - "n = 500\n", - "n_boostraps = 100\n", - "degree = 18 # A quite high value, just to show.\n", - "noise = 0.1\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-1, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n", - "\n", - "# Hold out some test data that is never used in training.\n", - "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "# Combine x transformation and model into one operation.\n", - "# Not neccesary, but convenient.\n", - "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", - "\n", - "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n", - "# for each bootstrap iteration.\n", - "y_pred = np.empty((y_test.shape[0], n_boostraps))\n", - "for i in range(n_boostraps):\n", - " x_, y_ = resample(x_train, y_train)\n", - "\n", - " # Evaluate the new model on the same test data each time.\n", - " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", - "\n", - "# Note: Expectations and variances taken w.r.t. different training\n", - "# data sets, hence the axis=1. Subsequent means are taken across the test data\n", - "# set in order to obtain a total value, but before this we have error/bias/variance\n", - "# calculated per data point in the test set.\n", - "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n", - "# maintains the column vector form. Dropping this yields very unexpected results.\n", - "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", - "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - "print('Error:', error)\n", - "print('Bias^2:', bias)\n", - "print('Var:', variance)\n", - "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n", - "\n", - "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n", - "plt.scatter(x_test, y_test, label='Data points')\n", - "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Understanding what happens" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "\n", - "np.random.seed(2018)\n", - "\n", - "n = 40\n", - "n_boostraps = 100\n", - "maxdegree = 14\n", - "\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", - "error = np.zeros(maxdegree)\n", - "bias = np.zeros(maxdegree)\n", - "variance = np.zeros(maxdegree)\n", - "polydegree = np.zeros(maxdegree)\n", - "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "for degree in range(maxdegree):\n", - " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", - " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", - " for i in range(n_boostraps):\n", - " x_, y_ = resample(x_train, y_train)\n", - " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", - "\n", - " polydegree[degree] = degree\n", - " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", - " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - " print('Polynomial degree:', degree)\n", - " print('Error:', error[degree])\n", - " print('Bias^2:', bias[degree])\n", - " print('Var:', variance[degree])\n", - " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", - "\n", - "plt.plot(polydegree, np.log10(error), label='Error')\n", - "plt.plot(polydegree, bias, label='bias')\n", - "plt.plot(polydegree, variance, label='Variance')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## Summing up\n", - "\n", - "\n", - "\n", - "\n", - "The bias-variance tradeoff summarizes the fundamental tension in\n", - "machine learning, particularly supervised learning, between the\n", - "complexity of a model and the amount of training data needed to train\n", - "it. Since data is often limited, in practice it is often useful to\n", - "use a less-complex model with higher bias, that is a model whose asymptotic\n", - "performance is worse than another model because it is easier to\n", - "train and less sensitive to sampling noise arising from having a\n", - "finite-sized training dataset (smaller variance). \n", - "\n", - "\n", - "\n", - "The above equations tell us that in\n", - "order to minimize the expected test error, we need to select a\n", - "statistical learning method that simultaneously achieves low variance\n", - "and low bias. Note that variance is inherently a nonnegative quantity,\n", - "and squared bias is also nonnegative. Hence, we see that the expected\n", - "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n", - "\n", - "\n", - "What do we mean by the variance and bias of a statistical learning\n", - "method? The variance refers to the amount by which our model would change if we\n", - "estimated it using a different training data set. Since the training\n", - "data are used to fit the statistical learning method, different\n", - "training data sets will result in a different estimate. But ideally the\n", - "estimate for our model should not vary too much between training\n", - "sets. However, if a method has high variance then small changes in\n", - "the training data can result in large changes in the model. In general, more\n", - "flexible statistical methods have higher variance.\n", - "\n", - "\n", - "## Another Example rom Scikit-Learn's Repository" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "\"\"\"\n", - "============================\n", - "Underfitting vs. Overfitting\n", - "============================\n", - "\n", - "This example demonstrates the problems of underfitting and overfitting and\n", - "how we can use linear regression with polynomial features to approximate\n", - "nonlinear functions. The plot shows the function that we want to approximate,\n", - "which is a part of the cosine function. In addition, the samples from the\n", - "real function and the approximations of different models are displayed. The\n", - "models have polynomial features of different degrees. We can see that a\n", - "linear function (polynomial with degree 1) is not sufficient to fit the\n", - "training samples. This is called **underfitting**. A polynomial of degree 4\n", - "approximates the true function almost perfectly. However, for higher degrees\n", - "the model will **overfit** the training data, i.e. it learns the noise of the\n", - "training data.\n", - "We evaluate quantitatively **overfitting** / **underfitting** by using\n", - "cross-validation. We calculate the mean squared error (MSE) on the validation\n", - "set, the higher, the less likely the model generalizes correctly from the\n", - "training data.\n", - "\"\"\"\n", - "\n", - "print(__doc__)\n", - "\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.pipeline import Pipeline\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.linear_model import LinearRegression\n", - "from sklearn.model_selection import cross_val_score\n", - "\n", - "\n", - "def true_fun(X):\n", - " return np.cos(1.5 * np.pi * X)\n", - "\n", - "np.random.seed(0)\n", - "\n", - "n_samples = 30\n", - "degrees = [1, 4, 15]\n", - "\n", - "X = np.sort(np.random.rand(n_samples))\n", - "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n", - "\n", - "plt.figure(figsize=(14, 5))\n", - "for i in range(len(degrees)):\n", - " ax = plt.subplot(1, len(degrees), i + 1)\n", - " plt.setp(ax, xticks=(), yticks=())\n", - "\n", - " polynomial_features = PolynomialFeatures(degree=degrees[i],\n", - " include_bias=False)\n", - " linear_regression = LinearRegression()\n", - " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n", - " (\"linear_regression\", linear_regression)])\n", - " pipeline.fit(X[:, np.newaxis], y)\n", - "\n", - " # Evaluate the models using crossvalidation\n", - " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n", - " scoring=\"neg_mean_squared_error\", cv=10)\n", - "\n", - " X_test = np.linspace(0, 1, 100)\n", - " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n", - " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n", - " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n", - " plt.xlabel(\"x\")\n", - " plt.ylabel(\"y\")\n", - " plt.xlim((0, 1))\n", - " plt.ylim((-2, 2))\n", - " plt.legend(loc=\"best\")\n", - " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n", - " degrees[i], -scores.mean(), scores.std()))\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The one-dimensional Ising model\n", - "\n", - "Let us bring back the Ising model again, but now with an additional\n", - "focus on Ridge and Lasso regression as well. We repeat some of the\n", - "basic parts of the Ising model and the setup of the training and test\n", - "data. The one-dimensional Ising model with nearest neighbor\n", - "interaction, no external field and a constant coupling constant $J$ is\n", - "given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " H = -J \\sum_{k}^L s_k s_{k + 1},\n", - "\\label{_auto17} \\tag{27}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $s_i \\in \\{-1, 1\\}$ and $s_{N + 1} = s_1$. The number of spins in the system is determined by $L$. For the one-dimensional system there is no phase transition.\n", - "\n", - "We will look at a system of $L = 40$ spins with a coupling constant of $J = 1$. To get enough training data we will generate 10000 states with their respective energies." - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from mpl_toolkits.axes_grid1 import make_axes_locatable\n", - "import seaborn as sns\n", - "import scipy.linalg as scl\n", - "from sklearn.model_selection import train_test_split\n", - "import sklearn.linear_model as skl\n", - "import tqdm\n", - "sns.set(color_codes=True)\n", - "cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')\n", - "\n", - "L = 40\n", - "n = int(1e4)\n", - "\n", - "spins = np.random.choice([-1, 1], size=(n, L))\n", - "J = 1.0\n", - "\n", - "energies = np.zeros(n)\n", - "\n", - "for i in range(n):\n", - " energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "A more general form for the one-dimensional Ising model is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " H = - \\sum_j^L \\sum_k^L s_j s_k J_{jk}.\n", - "\\label{_auto18} \\tag{28}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here we allow for interactions beyond the nearest neighbors and a more\n", - "adaptive coupling matrix. This latter expression can be formulated as\n", - "a matrix-product on the form" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " H = X J,\n", - "\\label{_auto19} \\tag{29}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $X_{jk} = s_j s_k$ and $J$ is the matrix consisting of the\n", - "elements $-J_{jk}$. This form of writing the energy fits perfectly\n", - "with the form utilized in linear regression, viz." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon}.\n", - "\\label{_auto20} \\tag{30}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We organize the data as we did above" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "X = np.zeros((n, L ** 2))\n", - "for i in range(n):\n", - " X[i] = np.outer(spins[i], spins[i]).ravel()\n", - "y = energies\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)\n", - "\n", - "X_train_own = np.concatenate(\n", - " (np.ones(len(X_train))[:, np.newaxis], X_train),\n", - " axis=1\n", - ")\n", - "\n", - "X_test_own = np.concatenate(\n", - " (np.ones(len(X_test))[:, np.newaxis], X_test),\n", - " axis=1\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We will do all fitting with **Scikit-Learn**," - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "clf = skl.LinearRegression().fit(X_train, y_train)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When extracting the $J$-matrix we make sure to remove the intercept" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "J_sk = clf.coef_.reshape(L, L)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And then we plot the results" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig = plt.figure(figsize=(20, 14))\n", - "im = plt.imshow(J_sk, **cmap_args)\n", - "plt.title(\"LinearRegression from Scikit-learn\", fontsize=18)\n", - "plt.xticks(fontsize=18)\n", - "plt.yticks(fontsize=18)\n", - "cb = fig.colorbar(im)\n", - "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The results perfectly with our previous discussion where we used our own code.\n", - "\n", - "## Ridge regression\n", - "\n", - "Having explored the ordinary least squares we move on to ridge\n", - "regression. In ridge regression we include a **regularizer**. This\n", - "involves a new cost function which leads to a new estimate for the\n", - "weights $\\boldsymbol{\\beta}$. This results in a penalized regression problem. The\n", - "cost function is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "1\n", - "6\n", - "8\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "_lambda = 0.1\n", - "clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)\n", - "J_ridge_sk = clf_ridge.coef_.reshape(L, L)\n", - "fig = plt.figure(figsize=(20, 14))\n", - "im = plt.imshow(J_ridge_sk, **cmap_args)\n", - "plt.title(\"Ridge from Scikit-learn\", fontsize=18)\n", - "plt.xticks(fontsize=18)\n", - "plt.yticks(fontsize=18)\n", - "cb = fig.colorbar(im)\n", - "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## LASSO regression\n", - "\n", - "In the **Least Absolute Shrinkage and Selection Operator** (LASSO)-method we get a third cost function." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " C(\\boldsymbol{X}, \\boldsymbol{\\beta}; \\lambda) = (\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})^T(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y}) + \\lambda \\sqrt{\\boldsymbol{\\beta}^T\\boldsymbol{\\beta}}.\n", - "\\label{_auto22} \\tag{32}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from **Scikit-Learn**." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)\n", - "J_lasso_sk = clf_lasso.coef_.reshape(L, L)\n", - "fig = plt.figure(figsize=(20, 14))\n", - "im = plt.imshow(J_lasso_sk, **cmap_args)\n", - "plt.title(\"Lasso from Scikit-learn\", fontsize=18)\n", - "plt.xticks(fontsize=18)\n", - "plt.yticks(fontsize=18)\n", - "cb = fig.colorbar(im)\n", - "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It is quite striking how LASSO breaks the symmetry of the coupling\n", - "constant as opposed to ridge and OLS. We get a sparse solution with\n", - "$J_{j, j + 1} = -1$.\n", - "\n", - "\n", - "\n", - "## Performance as function of the regularization parameter\n", - "\n", - "We see how the different models perform for a different set of values for $\\lambda$." - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "lambdas = np.logspace(-4, 5, 10)\n", - "\n", - "train_errors = {\n", - " \"ols_sk\": np.zeros(lambdas.size),\n", - " \"ridge_sk\": np.zeros(lambdas.size),\n", - " \"lasso_sk\": np.zeros(lambdas.size)\n", - "}\n", - "\n", - "test_errors = {\n", - " \"ols_sk\": np.zeros(lambdas.size),\n", - " \"ridge_sk\": np.zeros(lambdas.size),\n", - " \"lasso_sk\": np.zeros(lambdas.size)\n", - "}\n", - "\n", - "plot_counter = 1\n", - "\n", - "fig = plt.figure(figsize=(32, 54))\n", - "\n", - "for i, _lambda in enumerate(tqdm.tqdm(lambdas)):\n", - " for key, method in zip(\n", - " [\"ols_sk\", \"ridge_sk\", \"lasso_sk\"],\n", - " [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]\n", - " ):\n", - " method = method.fit(X_train, y_train)\n", - "\n", - " train_errors[key][i] = method.score(X_train, y_train)\n", - " test_errors[key][i] = method.score(X_test, y_test)\n", - "\n", - " omega = method.coef_.reshape(L, L)\n", - "\n", - " plt.subplot(10, 5, plot_counter)\n", - " plt.imshow(omega, **cmap_args)\n", - " plt.title(r\"%s, $\\lambda = %.4f$\" % (key, _lambda))\n", - " plot_counter += 1\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see that LASSO reaches a good solution for low\n", - "values of $\\lambda$, but will \"wither\" when we increase $\\lambda$ too\n", - "much. Ridge is more stable over a larger range of values for\n", - "$\\lambda$, but eventually also fades away.\n", - "\n", - "## Finding the optimal value of $\\lambda$\n", - "\n", - "To determine which value of $\\lambda$ is best we plot the accuracy of\n", - "the models when predicting the training and the testing set. We expect\n", - "the accuracy of the training set to be quite good, but if the accuracy\n", - "of the testing set is much lower this tells us that we might be\n", - "subject to an overfit model. The ideal scenario is an accuracy on the\n", - "testing set that is close to the accuracy of the training set." - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig = plt.figure(figsize=(20, 14))\n", - "\n", - "colors = {\n", - " \"ols_sk\": \"r\",\n", - " \"ridge_sk\": \"y\",\n", - " \"lasso_sk\": \"c\"\n", - "}\n", - "\n", - "for key in train_errors:\n", - " plt.semilogx(\n", - " lambdas,\n", - " train_errors[key],\n", - " colors[key],\n", - " label=\"Train {0}\".format(key),\n", - " linewidth=4.0\n", - " )\n", - "\n", - "for key in test_errors:\n", - " plt.semilogx(\n", - " lambdas,\n", - " test_errors[key],\n", - " colors[key] + \"--\",\n", - " label=\"Test {0}\".format(key),\n", - " linewidth=4.0\n", - " )\n", - "plt.legend(loc=\"best\", fontsize=18)\n", - "plt.xlabel(r\"$\\lambda$\", fontsize=18)\n", - "plt.ylabel(r\"$R^2$\", fontsize=18)\n", - "plt.tick_params(labelsize=18)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "From the above figure we can see that LASSO with $\\lambda = 10^{-2}$\n", - "achieves a very good accuracy on the test set. This by far surpasses the\n", - "other models for all values of $\\lambda$.\n", - "\n", - "\n", - "\n", - "## Further Exercises\n", - "\n", - "### Exercise 1\n", - "\n", - "We will 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)$.\n", - "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "x = np.random.rand(100,1)\n", - "y = 5*x*x+0.1*np.random.randn(100,1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial. \n", - "\n", - "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. \n", - "\n", - "3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the $R^2$ score function.\n", - "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have defined the mean value of $\\hat{y}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can use the functionality included in scikit-learn. If you feel\n", - "for it, you can use your own program and define functions which\n", - "compute the above two functions. Discuss the meaning of these\n", - "results. Try also to vary the coefficient in front of the added\n", - "stochastic noise term and discuss the quality of the fits.\n", - "\n", - "\n", - "\n", - "\n", - "### Exercise 2, variance of the parameters $\\beta$ in linear regression\n", - "\n", - "Show that the variance of the parameters $\\beta$ in the linear regression method (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)) is given as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{Var}(\\hat{\\beta}) = \\left(\\hat{X}^T\\hat{X}\\right)^{-1}\\sigma^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma^2 = \\frac{1}{N-p-1}\\sum_{i=1}^{N} (y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have assumed that we fit a function of degree $p-1$ (for example a polynomial in $x$). \n", - "\n", - "\n", - "\n", - "### Exercise 3\n", - "\n", - "This exercise is a continuation of exercise 1. 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. You can use the code under the Regression as an example on how to use the Ridge and the Lasso 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": 35, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "x = np.random.rand(100,1)\n", - "y = 5*x*x+0.1*np.random.randn(100,1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "1. Write your own code for the Ridge method and compute the parametrization for different values of $\\lambda$. Compare and analyze your results with those from exercise 1. Study the dependence on $\\lambda$ while also varying the strength of the noise in your expression for $y(x)$. \n", - "\n", - "2. Repeat the above but using the functionality of **scikit-learn**. Compare your code with the results from **scikit-learn**. Remember to run with the same random numbers for generating $x$ and $y$. \n", - "\n", - "3. Our next step is to study the variance of the parameters $\\beta_1$ and $\\beta_2$ (assuming that we are parametrizing 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 that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\\hat{X}^T\\hat{X})+\\lambda\\hat{I})^{-1}$) or use the functionality of **scikit-learn** and compute their variances. Discuss the results of these variances as functions \n", - "\n", - "4. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.\n", - "\n", - "5. Try to implement the cross-validation as well. \n", - "\n", - "6. Finally, using **scikit-learn** or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the $R^2$ score function.\n", - "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have defined the mean value of $\\hat{y}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Discuss these quantities as functions of the variable $\\lambda$ in the Ridge and Lasso regression methods. \n", - "\n", - "### Exercise 4\n", - "\n", - "We will study how\n", - "to fit polynomials to a specific two-dimensional function called\n", - "[Franke's\n", - "function](http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf). This\n", - "is a function which has been widely used when testing various interpolation and fitting\n", - "algorithms. Furthermore, after having established the model and the\n", - "method, we will employ resamling techniques such as the cross-validation and/or\n", - "the bootstrap methods, in order to perform a proper assessment of our models.\n", - "\n", - "\n", - "The Franke function, which is a weighted sum of four exponentials reads as follows" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "f(x,y) &= \\frac{3}{4}\\exp{\\left(-\\frac{(9x-2)^2}{4} - \\frac{(9y-2)^2}{4}\\right)}+\\frac{3}{4}\\exp{\\left(-\\frac{(9x+1)^2}{49}- \\frac{(9y+1)}{10}\\right)} \\\\\n", - "&+\\frac{1}{2}\\exp{\\left(-\\frac{(9x-7)^2}{4} - \\frac{(9y-3)^2}{4}\\right)} -\\frac{1}{5}\\exp{\\left(-(9x-4)^2 - (9y-7)^2\\right) }.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The function will be defined for $x,y\\in [0,1]$. Our first step will\n", - "be to perform an OLS regression analysis of this function, trying out\n", - "a polynomial fit with an $x$ and $y$ dependence of the form $[x, y,\n", - "x^2, y^2, xy, \\dots]$. We will also include cross-validation and\n", - "bootstrap as resampling techniques. As in homeworks 1 and 2, we\n", - "can use a uniform distribution to set up the arrays of values for $x$\n", - "and $y$, or as in the example below just a fix values for $x$ and $y$ with a given step size.\n", - "In this case we will have two predictors and need to fit a\n", - "function (for example a polynomial) of $x$ and $y$. Thereafter we will\n", - "repeat much of the same procedure using the the Ridge and\n", - "Lasso regression methods, introducing thus a dependence on the bias\n", - "(penalty) $\\lambda$.\n", - "\n", - "\n", - "The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it)" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from mpl_toolkits.mplot3d import Axes3D\n", - "import matplotlib.pyplot as plt\n", - "from matplotlib import cm\n", - "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", - "import numpy as np\n", - "from random import random, seed\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.gca(projection='3d')\n", - "\n", - "# Make data.\n", - "x = np.arange(0, 1, 0.05)\n", - "y = np.arange(0, 1, 0.05)\n", - "x, y = np.meshgrid(x,y)\n", - "\n", - "\n", - "def FrankeFunction(x,y):\n", - " term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", - " term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", - " term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", - " term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", - " return term1 + term2 + term3 + term4\n", - "\n", - "\n", - "z = FrankeFunction(x, y)\n", - "\n", - "# Plot the surface.\n", - "surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,\n", - " linewidth=0, antialiased=False)\n", - "\n", - "# Customize the z axis.\n", - "ax.set_zlim(-0.10, 1.40)\n", - "ax.zaxis.set_major_locator(LinearLocator(10))\n", - "ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n", - "\n", - "# Add a color bar which maps values to colors.\n", - "fig.colorbar(surf, shrink=0.5, aspect=5)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We will thus again generate our own dataset for a function $\\mathrm{FrankeFunction}(x,y)$ where \n", - "$x,y \\in [0,1]$ could be defined by random numbers computed with the uniform\n", - "distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition\n", - "an added stochastic noise to this function using the normal distribution $\\cal{N}(0,1)$.\n", - "\n", - "Write your own code (using either a matrix inversion or a singular value decomposition from e.g., **numpy** ) or use your code from exercises 1 and 3\n", - "and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\\beta$ by computing their variances, evaluate the Mean Squared error (MSE)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the $R^2$ score function.\n", - "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have defined the mean value of $\\hat{y}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm\n", - "and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models.\n", - "\n", - "\n", - "Write then your own code for the Ridge method, either using matrix\n", - "inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the\n", - "previous exercise (for the same polynomials and include resampling\n", - "techniques) but now for different values of $\\lambda$. Compare and\n", - "analyze your results with those obtained with standard OLS. Study the\n", - "dependence on $\\lambda$ while also varying eventually the strength of\n", - "the noise in your expression for $\\mathrm{FrankeFunction}(x,y)$.\n", - "\n", - "Then perform the same studies but now with Lasso regression. Use the functionalities of\n", - "**scikit-learn**. Give a critical discussion of the three methods and a\n", - "judgement of which model fits the data best." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/doc/src/Regression/Regression.log b/doc/src/Regression/Regression.log deleted file mode 100644 index e34c03458..000000000 --- a/doc/src/Regression/Regression.log +++ /dev/null @@ -1,2482 +0,0 @@ -This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015) (preloaded format=pdflatex 2015.5.24) 22 JUL 2019 20:11 -entering extended mode - \write18 enabled. - %&-line parsing enabled. -**Regression -(./Regression.tex -LaTeX2e <2015/01/01> -Babel <3.9l> and hyphenation patterns for 79 languages loaded. -(/usr/local/texlive/2015/texmf-dist/tex/latex/base/article.cls -Document Class: article 2014/09/29 v1.4h Standard LaTeX document class -(/usr/local/texlive/2015/texmf-dist/tex/latex/base/size10.clo -File: size10.clo 2014/09/29 v1.4h Standard LaTeX file (size option) -) -\c@part=\count79 -\c@section=\count80 -\c@subsection=\count81 -\c@subsubsection=\count82 -\c@paragraph=\count83 -\c@subparagraph=\count84 -\c@figure=\count85 -\c@table=\count86 -\abovecaptionskip=\skip41 -\belowcaptionskip=\skip42 -\bibindent=\dimen102 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/relsize/relsize.sty -Package: relsize 2013/03/29 ver 4.1 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/base/makeidx.sty -Package: makeidx 2014/09/29 v1.0m Standard LaTeX package -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/graphics/color.sty -Package: color 2014/10/28 v1.1a Standard LaTeX Color (DPC) - -(/usr/local/texlive/2015/texmf-dist/tex/latex/latexconfig/color.cfg -File: color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive -) -Package color Info: Driver file: pdftex.def on input line 142. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/pdftex-def/pdftex.def -File: pdftex.def 2011/05/27 v0.06d Graphics/color for pdfTeX - -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/infwarerr.sty -Package: infwarerr 2010/04/08 v1.3 Providing info/warning/error messages (HO) -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/ltxcmds.sty -Package: ltxcmds 2011/11/09 v1.22 LaTeX kernel commands for general use (HO) -) -\Gread@gobject=\count87 -)) -(/usr/local/texlive/2015/texmf-dist/tex/latex/setspace/setspace.sty -Package: setspace 2011/12/19 v6.7a set line spacing -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/amsmath/amsmath.sty -Package: amsmath 2013/01/14 v2.14 AMS math features -\@mathmargin=\skip43 - -For additional information on amsmath, use the `?' option. -(/usr/local/texlive/2015/texmf-dist/tex/latex/amsmath/amstext.sty -Package: amstext 2000/06/29 v2.01 - -(/usr/local/texlive/2015/texmf-dist/tex/latex/amsmath/amsgen.sty -File: amsgen.sty 1999/11/30 v2.0 -\@emptytoks=\toks14 -\ex@=\dimen103 -)) -(/usr/local/texlive/2015/texmf-dist/tex/latex/amsmath/amsbsy.sty -Package: amsbsy 1999/11/29 v1.2d -\pmbraise@=\dimen104 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/amsmath/amsopn.sty -Package: amsopn 1999/12/14 v2.01 operator names -) -\inf@bad=\count88 -LaTeX Info: Redefining \frac on input line 210. -\uproot@=\count89 -\leftroot@=\count90 -LaTeX Info: Redefining \overline on input line 306. -\classnum@=\count91 -\DOTSCASE@=\count92 -LaTeX Info: Redefining \ldots on input line 378. -LaTeX Info: Redefining \dots on input line 381. -LaTeX Info: Redefining \cdots on input line 466. -\Mathstrutbox@=\box26 -\strutbox@=\box27 -\big@size=\dimen105 -LaTeX Font Info: Redeclaring font encoding OML on input line 566. -LaTeX Font Info: Redeclaring font encoding OMS on input line 567. -\macc@depth=\count93 -\c@MaxMatrixCols=\count94 -\dotsspace@=\muskip10 -\c@parentequation=\count95 -\dspbrk@lvl=\count96 -\tag@help=\toks15 -\row@=\count97 -\column@=\count98 -\maxfields@=\count99 -\andhelp@=\toks16 -\eqnshift@=\dimen106 -\alignsep@=\dimen107 -\tagshift@=\dimen108 -\tagwidth@=\dimen109 -\totwidth@=\dimen110 -\lineht@=\dimen111 -\@envbody=\toks17 -\multlinegap=\skip44 -\multlinetaggap=\skip45 -\mathdisplay@stack=\toks18 -LaTeX Info: Redefining \[ on input line 2665. -LaTeX Info: Redefining \] on input line 2666. -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/amsfonts/amsfonts.sty -Package: amsfonts 2013/01/14 v3.01 Basic AMSFonts support -\symAMSa=\mathgroup4 -\symAMSb=\mathgroup5 -LaTeX Font Info: Overwriting math alphabet `\mathfrak' in version `bold' -(Font) U/euf/m/n --> U/euf/b/n on input line 106. -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/amsfonts/amssymb.sty -Package: amssymb 2013/01/14 v3.01 AMS font symbols -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/xcolor/xcolor.sty -Package: xcolor 2007/01/21 v2.11 LaTeX color extensions (UK) - -(/usr/local/texlive/2015/texmf-dist/tex/latex/latexconfig/color.cfg -File: color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive -) -Package xcolor Info: Driver file: pdftex.def on input line 225. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/colortbl/colortbl.sty -Package: colortbl 2012/02/13 v1.0a Color table columns (DPC) - -(/usr/local/texlive/2015/texmf-dist/tex/latex/tools/array.sty -Package: array 2014/10/28 v2.4c Tabular extension package (FMi) -\col@sep=\dimen112 -\extrarowheight=\dimen113 -\NC@list=\toks19 -\extratabsurround=\skip46 -\backup@length=\skip47 -) -\everycr=\toks20 -\minrowclearance=\skip48 -) -LaTeX Info: Redefining \color on input line 702. -\rownum=\count100 -Package xcolor Info: Model `cmy' substituted by `cmy0' on input line 1337. -Package xcolor Info: Model `hsb' substituted by `rgb' on input line 1341. -Package xcolor Info: Model `RGB' extended on input line 1353. -Package xcolor Info: Model `HTML' substituted by `rgb' on input line 1355. -Package xcolor Info: Model `Hsb' substituted by `hsb' on input line 1356. -Package xcolor Info: Model `tHsb' substituted by `hsb' on input line 1357. -Package xcolor Info: Model `HSB' substituted by `hsb' on input line 1358. -Package xcolor Info: Model `Gray' substituted by `gray' on input line 1359. -Package xcolor Info: Model `wave' substituted by `hsb' on input line 1360. -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/tools/bm.sty -Package: bm 2014/10/28 v1.1c Bold Symbol Support (DPC/FMi) -\symboldoperators=\mathgroup6 -\symboldletters=\mathgroup7 -\symboldsymbols=\mathgroup8 -LaTeX Font Info: Redeclaring math alphabet \mathbf on input line 141. -LaTeX Info: Redefining \bm on input line 207. -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/ltablex/ltablex.sty -Package: ltablex 2014/08/13 v1.1 Modified tabularx - -(/usr/local/texlive/2015/texmf-dist/tex/latex/tools/longtable.sty -Package: longtable 2014/10/28 v4.11 Multi-page Table package (DPC) -\LTleft=\skip49 -\LTright=\skip50 -\LTpre=\skip51 -\LTpost=\skip52 -\LTchunksize=\count101 -\LTcapwidth=\dimen114 -\LT@head=\box28 -\LT@firsthead=\box29 -\LT@foot=\box30 -\LT@lastfoot=\box31 -\LT@cols=\count102 -\LT@rows=\count103 -\c@LT@tables=\count104 -\c@LT@chunks=\count105 -\LT@p@ftn=\toks21 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/tools/tabularx.sty -Package: tabularx 2014/10/28 v2.10 `tabularx' package (DPC) -\TX@col@width=\dimen115 -\TX@old@table=\dimen116 -\TX@old@col=\dimen117 -\TX@target=\dimen118 -\TX@delta=\dimen119 -\TX@cols=\count106 -\TX@ftn=\toks22 -)) -(/usr/local/texlive/2015/texmf-dist/tex/latex/microtype/microtype.sty -Package: microtype 2013/05/23 v2.5a Micro-typographical refinements (RS) - -(/usr/local/texlive/2015/texmf-dist/tex/latex/graphics/keyval.sty -Package: keyval 2014/10/28 v1.15 key=value parser (DPC) -\KV@toks@=\toks23 -) -\MT@toks=\toks24 -\MT@count=\count107 -LaTeX Info: Redefining \textls on input line 766. -\MT@outer@kern=\dimen120 -LaTeX Info: Redefining \textmicrotypecontext on input line 1285. -\MT@listname@count=\count108 - -(/usr/local/texlive/2015/texmf-dist/tex/latex/microtype/microtype-pdftex.def -File: microtype-pdftex.def 2013/05/23 v2.5a Definitions specific to pdftex (RS) - -LaTeX Info: Redefining \lsstyle on input line 915. -LaTeX Info: Redefining \lslig on input line 915. -\MT@outer@space=\skip53 -) -Package microtype Info: Loading configuration file microtype.cfg. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/microtype/microtype.cfg -File: microtype.cfg 2013/05/23 v2.5a microtype main configuration file (RS) -)) -(/usr/local/texlive/2015/texmf-dist/tex/latex/graphics/graphicx.sty -Package: graphicx 2014/10/28 v1.0g Enhanced LaTeX Graphics (DPC,SPQR) - -(/usr/local/texlive/2015/texmf-dist/tex/latex/graphics/graphics.sty -Package: graphics 2014/10/28 v1.0p Standard LaTeX Graphics (DPC,SPQR) - -(/usr/local/texlive/2015/texmf-dist/tex/latex/graphics/trig.sty -Package: trig 1999/03/16 v1.09 sin cos tan (DPC) -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/latexconfig/graphics.cfg -File: graphics.cfg 2010/04/23 v1.9 graphics configuration of TeX Live -) -Package graphics Info: Driver file: pdftex.def on input line 94. -) -\Gin@req@height=\dimen121 -\Gin@req@width=\dimen122 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/fancyvrb/fancyvrb.sty -Package: fancyvrb 2008/02/07 - -Style option: `fancyvrb' v2.7a, with DG/SPQR fixes, and firstline=lastline fix -<2008/02/07> (tvz) -\FV@CodeLineNo=\count109 -\FV@InFile=\read1 -\FV@TabBox=\box32 -\c@FancyVerbLine=\count110 -\FV@StepNumber=\count111 -\FV@OutFile=\write3 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/minted/minted.sty -Package: minted 2015/01/31 v2.0 Yet another Pygments shim for LaTeX - -(/usr/local/texlive/2015/texmf-dist/tex/latex/oberdiek/kvoptions.sty -Package: kvoptions 2011/06/30 v3.11 Key value format for package options (HO) - -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/kvsetkeys.sty -Package: kvsetkeys 2012/04/25 v1.16 Key value parser (HO) - -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/etexcmds.sty -Package: etexcmds 2011/02/16 v1.5 Avoid name clashes with e-TeX commands (HO) - -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/ifluatex.sty -Package: ifluatex 2010/03/01 v1.3 Provides the ifluatex switch (HO) -Package ifluatex Info: LuaTeX not detected. -) -Package etexcmds Info: Could not find \expanded. -(etexcmds) That can mean that you are not using pdfTeX 1.50 or -(etexcmds) that some package has redefined \expanded. -(etexcmds) In the latter case, load this package earlier. -))) -(/usr/local/texlive/2015/texmf-dist/tex/latex/float/float.sty -Package: float 2001/11/08 v1.3d Float enhancements (AL) -\c@float@type=\count112 -\float@exts=\toks25 -\float@box=\box33 -\@float@everytoks=\toks26 -\@floatcapt=\box34 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/base/ifthen.sty -Package: ifthen 2014/09/29 v1.1c Standard LaTeX ifthen package (DPC) -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/tools/calc.sty -Package: calc 2014/10/28 v4.3 Infix arithmetic (KKT,FJ) -\calc@Acount=\count113 -\calc@Bcount=\count114 -\calc@Adimen=\dimen123 -\calc@Bdimen=\dimen124 -\calc@Askip=\skip54 -\calc@Bskip=\skip55 -LaTeX Info: Redefining \setlength on input line 80. -LaTeX Info: Redefining \addtolength on input line 81. -\calc@Ccount=\count115 -\calc@Cskip=\skip56 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/ifplatform/ifplatform.sty -Package: ifplatform 2010/10/22 v0.4 Testing for the operating system - -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/pdftexcmds.sty -Package: pdftexcmds 2011/11/29 v0.20 Utility functions of pdfTeX for LuaTeX (HO -) - -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/ifpdf.sty -Package: ifpdf 2011/01/30 v2.3 Provides the ifpdf switch (HO) -Package ifpdf Info: pdfTeX in PDF mode is detected. -) -Package pdftexcmds Info: LuaTeX not detected. -Package pdftexcmds Info: \pdf@primitive is available. -Package pdftexcmds Info: \pdf@ifprimitive is available. -Package pdftexcmds Info: \pdfdraftmode found. -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/catchfile.sty -Package: catchfile 2011/03/01 v1.6 Catch the contents of a file (HO) -) -runsystem(uname -s > "Regression.w18")...executed. - - -(./Regression.w18) -runsystem(rm -- "Regression.w18")...executed. - -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/etoolbox/etoolbox.sty -Package: etoolbox 2015/05/04 v2.2 e-TeX tools for LaTeX (JAW) -\etb@tempcnta=\count116 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/xstring/xstring.sty -(/usr/local/texlive/2015/texmf-dist/tex/generic/xstring/xstring.tex -\@xs@message=\write4 -\integerpart=\count117 -\decimalpart=\count118 -) -Package: xstring 2013/10/13 v1.7c String manipulations (C Tellechea) -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/lineno/lineno.sty -Package: lineno 2005/11/02 line numbers on paragraphs v4.41 -\linenopenalty=\count119 -\output=\toks27 -\linenoprevgraf=\count120 -\linenumbersep=\dimen125 -\linenumberwidth=\dimen126 -\c@linenumber=\count121 -\c@pagewiselinenumber=\count122 -\c@LN@truepage=\count123 -\c@internallinenumber=\count124 -\c@internallinenumbers=\count125 -\quotelinenumbersep=\dimen127 -\bframerule=\dimen128 -\bframesep=\dimen129 -\bframebox=\box35 -LaTeX Info: Redefining \\ on input line 3056. -) -\minted@appexistsfile=\read2 -\FV@BreakIndent=\dimen130 -\FV@BreakSymbolSepLeft=\dimen131 -\FV@BreakSymbolSepRight=\dimen132 -\FV@BreakSymbolIndentLeft=\dimen133 -\FV@BreakSymbolIndentRight=\dimen134 -\c@FancyVerbLineBreakLast=\count126 -\FV@LineBox=\box36 -\FV@LineIndentBox=\box37 -\minted@bgbox=\box38 -\minted@code=\write5 -\c@minted@FancyVerbLineTemp=\count127 -\@float@every@listing=\toks28 -\c@listing=\count128 -) -runsystem(mkdir -p "_minted-Regression")...executed. - -runsystem(which "pygmentize" && touch "Regression.aex")...executed. - -runsystem(rm "Regression.aex")...executed. - - -(./_minted-Regression/default.pygstyle) -(/usr/local/texlive/2015/texmf-dist/tex/latex/base/fontenc.sty -Package: fontenc 2005/09/27 v1.99g Standard LaTeX package - -(/usr/local/texlive/2015/texmf-dist/tex/latex/base/t1enc.def -File: t1enc.def 2005/09/27 v1.99g Standard LaTeX file -LaTeX Font Info: Redeclaring font encoding T1 on input line 48. -)) -(/usr/local/texlive/2015/texmf-dist/tex/latex/ucs/ucs.sty -Package: ucs 2013/05/11 v2.2 UCS: Unicode input support - -(/usr/local/texlive/2015/texmf-dist/tex/latex/ucs/data/uni-global.def -File: uni-global.def 2013/05/13 UCS: Unicode global data -) -\uc@secondtry=\count129 -\uc@combtoks=\toks29 -\uc@combtoksb=\toks30 -\uc@temptokena=\toks31 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/base/inputenc.sty -Package: inputenc 2015/03/17 v1.2c Input encoding file -\inpenc@prehook=\toks32 -\inpenc@posthook=\toks33 - -(/usr/local/texlive/2015/texmf-dist/tex/latex/ucs/utf8x.def -File: utf8x.def 2004/10/17 UCS: Input encoding UTF-8 -)) -(/usr/local/texlive/2015/texmf-dist/tex/latex/lm/lmodern.sty -Package: lmodern 2009/10/30 v1.6 Latin Modern Fonts -LaTeX Font Info: Overwriting symbol font `operators' in version `normal' -(Font) OT1/cmr/m/n --> OT1/lmr/m/n on input line 22. -LaTeX Font Info: Overwriting symbol font `letters' in version `normal' -(Font) OML/cmm/m/it --> OML/lmm/m/it on input line 23. -LaTeX Font Info: Overwriting symbol font `symbols' in version `normal' -(Font) OMS/cmsy/m/n --> OMS/lmsy/m/n on input line 24. -LaTeX Font Info: Overwriting symbol font `largesymbols' in version `normal' -(Font) OMX/cmex/m/n --> OMX/lmex/m/n on input line 25. -LaTeX Font Info: Overwriting symbol font `operators' in version `bold' -(Font) OT1/cmr/bx/n --> OT1/lmr/bx/n on input line 26. -LaTeX Font Info: Overwriting symbol font `letters' in version `bold' -(Font) OML/cmm/b/it --> OML/lmm/b/it on input line 27. -LaTeX Font Info: Overwriting symbol font `symbols' in version `bold' -(Font) OMS/cmsy/b/n --> OMS/lmsy/b/n on input line 28. -LaTeX Font Info: Overwriting symbol font `largesymbols' in version `bold' -(Font) OMX/cmex/m/n --> OMX/lmex/m/n on input line 29. -LaTeX Font Info: Overwriting math alphabet `\mathbf' in version `normal' -(Font) OT1/cmr/bx/n --> OT1/lmr/bx/n on input line 31. -LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `normal' -(Font) OT1/cmss/m/n --> OT1/lmss/m/n on input line 32. -LaTeX Font Info: Overwriting math alphabet `\mathit' in version `normal' -(Font) OT1/cmr/m/it --> OT1/lmr/m/it on input line 33. -LaTeX Font Info: Overwriting math alphabet `\mathtt' in version `normal' -(Font) OT1/cmtt/m/n --> OT1/lmtt/m/n on input line 34. -LaTeX Font Info: Overwriting math alphabet `\mathbf' in version `bold' -(Font) OT1/cmr/bx/n --> OT1/lmr/bx/n on input line 35. -LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `bold' -(Font) OT1/cmss/bx/n --> OT1/lmss/bx/n on input line 36. -LaTeX Font Info: Overwriting math alphabet `\mathit' in version `bold' -(Font) OT1/cmr/bx/it --> OT1/lmr/bx/it on input line 37. -LaTeX Font Info: Overwriting math alphabet `\mathtt' in version `bold' -(Font) OT1/cmtt/m/n --> OT1/lmtt/m/n on input line 38. -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/hyperref/hyperref.sty -Package: hyperref 2012/11/06 v6.83m Hypertext links for LaTeX - -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/hobsub-hyperref.sty -Package: hobsub-hyperref 2012/05/28 v1.13 Bundle oberdiek, subset hyperref (HO) - - -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/hobsub-generic.sty -Package: hobsub-generic 2012/05/28 v1.13 Bundle oberdiek, subset generic (HO) -Package: hobsub 2012/05/28 v1.13 Construct package bundles (HO) -Package hobsub Info: Skipping package `infwarerr' (already loaded). -Package hobsub Info: Skipping package `ltxcmds' (already loaded). -Package hobsub Info: Skipping package `ifluatex' (already loaded). -Package: ifvtex 2010/03/01 v1.5 Detect VTeX and its facilities (HO) -Package ifvtex Info: VTeX not detected. -Package: intcalc 2007/09/27 v1.1 Expandable calculations with integers (HO) -Package hobsub Info: Skipping package `ifpdf' (already loaded). -Package hobsub Info: Skipping package `etexcmds' (already loaded). -Package hobsub Info: Skipping package `kvsetkeys' (already loaded). -Package: kvdefinekeys 2011/04/07 v1.3 Define keys (HO) -Package hobsub Info: Skipping package `pdftexcmds' (already loaded). -Package: pdfescape 2011/11/25 v1.13 Implements pdfTeX's escape features (HO) -Package: bigintcalc 2012/04/08 v1.3 Expandable calculations on big integers (HO -) -Package: bitset 2011/01/30 v1.1 Handle bit-vector datatype (HO) -Package: uniquecounter 2011/01/30 v1.2 Provide unlimited unique counter (HO) -) -Package hobsub Info: Skipping package `hobsub' (already loaded). -Package: letltxmacro 2010/09/02 v1.4 Let assignment for LaTeX macros (HO) -Package: hopatch 2012/05/28 v1.2 Wrapper for package hooks (HO) -Package: xcolor-patch 2011/01/30 xcolor patch -Package: atveryend 2011/06/30 v1.8 Hooks at the very end of document (HO) -Package: atbegshi 2011/10/05 v1.16 At begin shipout hook (HO) -Package: refcount 2011/10/16 v3.4 Data extraction from label references (HO) -Package: hycolor 2011/01/30 v1.7 Color options for hyperref/bookmark (HO) -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/ifxetex/ifxetex.sty -Package: ifxetex 2010/09/12 v0.6 Provides ifxetex conditional -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/oberdiek/auxhook.sty -Package: auxhook 2011/03/04 v1.3 Hooks for auxiliary files (HO) -) -\@linkdim=\dimen135 -\Hy@linkcounter=\count130 -\Hy@pagecounter=\count131 - -(/usr/local/texlive/2015/texmf-dist/tex/latex/hyperref/pd1enc.def -File: pd1enc.def 2012/11/06 v6.83m Hyperref: PDFDocEncoding definition (HO) -) -\Hy@SavedSpaceFactor=\count132 - -(/usr/local/texlive/2015/texmf-dist/tex/latex/latexconfig/hyperref.cfg -File: hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive -) -Package hyperref Info: Option `final' set `true' on input line 4319. -Package hyperref Info: Hyper figures OFF on input line 4443. -Package hyperref Info: Link nesting OFF on input line 4448. -Package hyperref Info: Hyper index ON on input line 4451. -Package hyperref Info: Plain pages OFF on input line 4458. -Package hyperref Info: Backreferencing OFF on input line 4463. -Package hyperref Info: Implicit mode ON; LaTeX internals redefined. -Package hyperref Info: Bookmarks ON on input line 4688. -\c@Hy@tempcnt=\count133 - -(/usr/local/texlive/2015/texmf-dist/tex/latex/url/url.sty -\Urlmuskip=\muskip11 -Package: url 2013/09/16 ver 3.4 Verb mode for urls, etc. -) -LaTeX Info: Redefining \url on input line 5041. -\XeTeXLinkMargin=\dimen136 -\Fld@menulength=\count134 -\Field@Width=\dimen137 -\Fld@charsize=\dimen138 -Package hyperref Info: Hyper figures OFF on input line 6295. -Package hyperref Info: Link nesting OFF on input line 6300. -Package hyperref Info: Hyper index ON on input line 6303. -Package hyperref Info: backreferencing OFF on input line 6310. -Package hyperref Info: Link coloring OFF on input line 6315. -Package hyperref Info: Link coloring with OCG OFF on input line 6320. -Package hyperref Info: PDF/A mode OFF on input line 6325. -LaTeX Info: Redefining \ref on input line 6365. -LaTeX Info: Redefining \pageref on input line 6369. -\Hy@abspage=\count135 -\c@Item=\count136 -\c@Hfootnote=\count137 -) - -Package hyperref Message: Driver (autodetected): hpdftex. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/hyperref/hpdftex.def -File: hpdftex.def 2012/11/06 v6.83m Hyperref driver for pdfTeX -\Fld@listcount=\count138 -\c@bookmark@seq@number=\count139 - -(/usr/local/texlive/2015/texmf-dist/tex/latex/oberdiek/rerunfilecheck.sty -Package: rerunfilecheck 2011/04/15 v1.7 Rerun checks for auxiliary files (HO) -Package uniquecounter Info: New unique counter `rerunfilecheck' on input line 2 -82. -) -\Hy@SectionHShift=\skip57 -) -Package hyperref Info: Option `breaklinks' set `true' on input line 48. -Package hyperref Info: Option `colorlinks' set `true' on input line 48. -Package hyperref Info: Option `pdfmenubar' set `true' on input line 48. -Package hyperref Info: Option `pdftoolbar' set `true' on input line 48. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/fancyhdr/fancyhdr.sty -\fancy@headwidth=\skip58 -\f@ncyO@elh=\skip59 -\f@ncyO@erh=\skip60 -\f@ncyO@olh=\skip61 -\f@ncyO@orh=\skip62 -\f@ncyO@elf=\skip63 -\f@ncyO@erf=\skip64 -\f@ncyO@olf=\skip65 -\f@ncyO@orf=\skip66 -) - -Package Fancyhdr Warning: \fancyfoot's `E' option without twoside option is use -less on input line 57. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/mdframed/mdframed.sty -Package: mdframed 2013/07/01 1.9b: mdframed - -(/usr/local/texlive/2015/texmf-dist/tex/latex/l3packages/xparse/xparse.sty -(/usr/local/texlive/2015/texmf-dist/tex/latex/l3kernel/expl3.sty -Package: expl3 2015/03/01 v5547 L3 programming layer (loader) - -(/usr/local/texlive/2015/texmf-dist/tex/latex/l3kernel/expl3-code.tex -Package: expl3 2015/03/01 v5547 L3 programming layer (code) -L3 Module: l3bootstrap 2015/02/28 v5542 L3 Bootstrap code -L3 Module: l3names 2015/02/24 v5535 L3 Namespace for primitives -L3 Module: l3basics 2015/01/27 v5500 L3 Basic definitions -L3 Module: l3expan 2014/11/27 v5472 L3 Argument expansion -L3 Module: l3tl 2015/01/27 v5500 L3 Token lists -L3 Module: l3str 2015/03/01 v5545 L3 Strings -L3 Module: l3seq 2014/08/23 v5354 L3 Sequences and stacks -L3 Module: l3int 2015/02/21 v5529 L3 Integers -\c_max_int=\count140 -\l_tmpa_int=\count141 -\l_tmpb_int=\count142 -\g_tmpa_int=\count143 -\g_tmpb_int=\count144 -L3 Module: l3quark 2014/08/23 v5354 L3 Quarks -L3 Module: l3prg 2014/08/23 v5354 L3 Control structures -\g__prg_map_int=\count145 -L3 Module: l3clist 2014/08/23 v5354 L3 Comma separated lists -L3 Module: l3token 2014/09/15 v5422 L3 Experimental token manipulation -L3 Module: l3prop 2014/08/23 v5354 L3 Property lists -L3 Module: l3msg 2015/02/26 v5537 L3 Messages -L3 Module: l3file 2014/08/24 v5369 L3 File and I/O operations -\l_iow_line_count_int=\count146 -\l__iow_target_count_int=\count147 -\l__iow_current_line_int=\count148 -\l__iow_current_word_int=\count149 -\l__iow_current_indentation_int=\count150 -L3 Module: l3skip 2014/08/23 v5354 L3 Dimensions and skips -\c_zero_dim=\dimen139 -\c_max_dim=\dimen140 -\l_tmpa_dim=\dimen141 -\l_tmpb_dim=\dimen142 -\g_tmpa_dim=\dimen143 -\g_tmpb_dim=\dimen144 -\c_zero_skip=\skip67 -\c_max_skip=\skip68 -\l_tmpa_skip=\skip69 -\l_tmpb_skip=\skip70 -\g_tmpa_skip=\skip71 -\g_tmpb_skip=\skip72 -\c_zero_muskip=\muskip12 -\c_max_muskip=\muskip13 -\l_tmpa_muskip=\muskip14 -\l_tmpb_muskip=\muskip15 -\g_tmpa_muskip=\muskip16 -\g_tmpb_muskip=\muskip17 -L3 Module: l3keys 2015/01/27 v5500 L3 Key-value interfaces -\g__keyval_level_int=\count151 -\l_keys_choice_int=\count152 -L3 Module: l3fp 2014/08/22 v5336 L3 Floating points -\c__fp_leading_shift_int=\count153 -\c__fp_middle_shift_int=\count154 -\c__fp_trailing_shift_int=\count155 -\c__fp_big_leading_shift_int=\count156 -\c__fp_big_middle_shift_int=\count157 -\c__fp_big_trailing_shift_int=\count158 -\c__fp_Bigg_leading_shift_int=\count159 -\c__fp_Bigg_middle_shift_int=\count160 -\c__fp_Bigg_trailing_shift_int=\count161 -L3 Module: l3box 2014/08/23 v5354 L3 Experimental boxes -\c_empty_box=\box39 -\l_tmpa_box=\box40 -\l_tmpb_box=\box41 -\g_tmpa_box=\box42 -\g_tmpb_box=\box43 -L3 Module: l3coffins 2014/08/23 v5354 L3 Coffin code layer -\l__coffin_internal_box=\box44 -\l__coffin_internal_dim=\dimen145 -\l__coffin_offset_x_dim=\dimen146 -\l__coffin_offset_y_dim=\dimen147 -\l__coffin_x_dim=\dimen148 -\l__coffin_y_dim=\dimen149 -\l__coffin_x_prime_dim=\dimen150 -\l__coffin_y_prime_dim=\dimen151 -\c_empty_coffin=\box45 -\l__coffin_aligned_coffin=\box46 -\l__coffin_aligned_internal_coffin=\box47 -\l_tmpa_coffin=\box48 -\l_tmpb_coffin=\box49 -\l__coffin_display_coffin=\box50 -\l__coffin_display_coord_coffin=\box51 -\l__coffin_display_pole_coffin=\box52 -\l__coffin_display_offset_dim=\dimen152 -\l__coffin_display_x_dim=\dimen153 -\l__coffin_display_y_dim=\dimen154 -L3 Module: l3color 2014/08/23 v5354 L3 Experimental color support -L3 Module: l3candidates 2015/03/01 v5544 L3 Experimental additions to l3kernel -\l__box_top_dim=\dimen155 -\l__box_bottom_dim=\dimen156 -\l__box_left_dim=\dimen157 -\l__box_right_dim=\dimen158 -\l__box_top_new_dim=\dimen159 -\l__box_bottom_new_dim=\dimen160 -\l__box_left_new_dim=\dimen161 -\l__box_right_new_dim=\dimen162 -\l__box_internal_box=\box53 -\l__coffin_bounding_shift_dim=\dimen163 -\l__coffin_left_corner_dim=\dimen164 -\l__coffin_right_corner_dim=\dimen165 -\l__coffin_bottom_corner_dim=\dimen166 -\l__coffin_top_corner_dim=\dimen167 -\l__coffin_scaled_total_height_dim=\dimen168 -\l__coffin_scaled_width_dim=\dimen169 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/l3kernel/l3unicode-data.def -File: l3unicode-data.def 2015/03/01 v5544 L3 Unicode data -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/l3kernel/l3pdfmode.def -File: l3pdfmode.def 2015/03/01 v5544 L3 Experimental driver: PDF mode -\l__driver_color_stack_int=\count162 -)) -Package: xparse 2014/11/25 v5471 L3 Experimental document command parser -\l__xparse_current_arg_int=\count163 -\l__xparse_m_args_int=\count164 -\l__xparse_mandatory_args_int=\count165 -\l__xparse_processor_int=\count166 -\l__xparse_v_nesting_int=\count167 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/oberdiek/zref-abspage.sty -Package: zref-abspage 2012/04/04 v2.24 Module abspage for zref (HO) - -(/usr/local/texlive/2015/texmf-dist/tex/latex/oberdiek/zref-base.sty -Package: zref-base 2012/04/04 v2.24 Module base for zref (HO) -Package zref Info: New property list: main on input line 759. -Package zref Info: New property: default on input line 760. -Package zref Info: New property: page on input line 761. -) -\c@abspage=\count168 -Package zref Info: New property: abspage on input line 62. -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/needspace/needspace.sty -Package: needspace 2010/09/12 v1.3d reserve vertical space -) -\mdf@templength=\skip73 -\c@mdf@globalstyle@cnt=\count169 -\mdf@skipabove@length=\skip74 -\mdf@skipbelow@length=\skip75 -\mdf@leftmargin@length=\skip76 -\mdf@rightmargin@length=\skip77 -\mdf@innerleftmargin@length=\skip78 -\mdf@innerrightmargin@length=\skip79 -\mdf@innertopmargin@length=\skip80 -\mdf@innerbottommargin@length=\skip81 -\mdf@splittopskip@length=\skip82 -\mdf@splitbottomskip@length=\skip83 -\mdf@outermargin@length=\skip84 -\mdf@innermargin@length=\skip85 -\mdf@linewidth@length=\skip86 -\mdf@innerlinewidth@length=\skip87 -\mdf@middlelinewidth@length=\skip88 -\mdf@outerlinewidth@length=\skip89 -\mdf@roundcorner@length=\skip90 -\mdf@footenotedistance@length=\skip91 -\mdf@userdefinedwidth@length=\skip92 -\mdf@needspace@length=\skip93 -\mdf@frametitleaboveskip@length=\skip94 -\mdf@frametitlebelowskip@length=\skip95 -\mdf@frametitlerulewidth@length=\skip96 -\mdf@frametitleleftmargin@length=\skip97 -\mdf@frametitlerightmargin@length=\skip98 -\mdf@shadowsize@length=\skip99 -\mdf@extratopheight@length=\skip100 -\mdf@subtitleabovelinewidth@length=\skip101 -\mdf@subtitlebelowlinewidth@length=\skip102 -\mdf@subtitleaboveskip@length=\skip103 -\mdf@subtitlebelowskip@length=\skip104 -\mdf@subtitleinneraboveskip@length=\skip105 -\mdf@subtitleinnerbelowskip@length=\skip106 -\mdf@subsubtitleabovelinewidth@length=\skip107 -\mdf@subsubtitlebelowlinewidth@length=\skip108 -\mdf@subsubtitleaboveskip@length=\skip109 -\mdf@subsubtitlebelowskip@length=\skip110 -\mdf@subsubtitleinneraboveskip@length=\skip111 -\mdf@subsubtitleinnerbelowskip@length=\skip112 - -(/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/frontendlayer/tikz.sty -(/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/basiclayer/pgf.sty -(/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/utilities/pgfrcs.sty -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/utilities/pgfutil-common.te -x -\pgfutil@everybye=\toks34 -\pgfutil@tempdima=\dimen170 -\pgfutil@tempdimb=\dimen171 - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/utilities/pgfutil-common-li -sts.tex)) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/utilities/pgfutil-latex.def -\pgfutil@abb=\box54 -(/usr/local/texlive/2015/texmf-dist/tex/latex/ms/everyshi.sty -Package: everyshi 2001/05/15 v3.00 EveryShipout Package (MS) -)) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/utilities/pgfrcs.code.tex -Package: pgfrcs 2013/12/20 v3.0.0 (rcs-revision 1.28) -)) -Package: pgf 2013/12/18 v3.0.0 (rcs-revision 1.14) -(/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/basiclayer/pgfcore.sty -(/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/systemlayer/pgfsys.sty -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/systemlayer/pgfsys.code.tex -Package: pgfsys 2013/11/30 v3.0.0 (rcs-revision 1.47) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/utilities/pgfkeys.code.tex -\pgfkeys@pathtoks=\toks35 -\pgfkeys@temptoks=\toks36 - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/utilities/pgfkeysfiltered.c -ode.tex -\pgfkeys@tmptoks=\toks37 -)) -\pgf@x=\dimen172 -\pgf@y=\dimen173 -\pgf@xa=\dimen174 -\pgf@ya=\dimen175 -\pgf@xb=\dimen176 -\pgf@yb=\dimen177 -\pgf@xc=\dimen178 -\pgf@yc=\dimen179 -\w@pgf@writea=\write6 -\r@pgf@reada=\read3 -\c@pgf@counta=\count170 -\c@pgf@countb=\count171 -\c@pgf@countc=\count172 -\c@pgf@countd=\count173 -\t@pgf@toka=\toks38 -\t@pgf@tokb=\toks39 -\t@pgf@tokc=\toks40 - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/systemlayer/pgf.cfg -File: pgf.cfg 2008/05/14 (rcs-revision 1.7) -) -Driver file for pgf: pgfsys-pdftex.def - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/systemlayer/pgfsys-pdftex.d -ef -File: pgfsys-pdftex.def 2013/07/18 (rcs-revision 1.33) - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/systemlayer/pgfsys-common-p -df.def -File: pgfsys-common-pdf.def 2013/10/10 (rcs-revision 1.13) -))) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/systemlayer/pgfsyssoftpath. -code.tex -File: pgfsyssoftpath.code.tex 2013/09/09 (rcs-revision 1.9) -\pgfsyssoftpath@smallbuffer@items=\count174 -\pgfsyssoftpath@bigbuffer@items=\count175 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/systemlayer/pgfsysprotocol. -code.tex -File: pgfsysprotocol.code.tex 2006/10/16 (rcs-revision 1.4) -)) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcore.code.tex -Package: pgfcore 2010/04/11 v3.0.0 (rcs-revision 1.7) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmath.code.tex -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathcalc.code.tex -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathutil.code.tex) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathparser.code.tex -\pgfmath@dimen=\dimen180 -\pgfmath@count=\count176 -\pgfmath@box=\box55 -\pgfmath@toks=\toks41 -\pgfmath@stack@operand=\toks42 -\pgfmath@stack@operation=\toks43 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfunctions.code. -tex -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfunctions.basic -.code.tex) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfunctions.trigo -nometric.code.tex) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfunctions.rando -m.code.tex) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfunctions.compa -rison.code.tex) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfunctions.base. -code.tex) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfunctions.round -.code.tex) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfunctions.misc. -code.tex) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfunctions.integ -erarithmetics.code.tex))) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmathfloat.code.tex -\c@pgfmathroundto@lastzeros=\count177 -)) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcorepoints.co -de.tex -File: pgfcorepoints.code.tex 2013/10/07 (rcs-revision 1.27) -\pgf@picminx=\dimen181 -\pgf@picmaxx=\dimen182 -\pgf@picminy=\dimen183 -\pgf@picmaxy=\dimen184 -\pgf@pathminx=\dimen185 -\pgf@pathmaxx=\dimen186 -\pgf@pathminy=\dimen187 -\pgf@pathmaxy=\dimen188 -\pgf@xx=\dimen189 -\pgf@xy=\dimen190 -\pgf@yx=\dimen191 -\pgf@yy=\dimen192 -\pgf@zx=\dimen193 -\pgf@zy=\dimen194 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcorepathconst -ruct.code.tex -File: pgfcorepathconstruct.code.tex 2013/10/07 (rcs-revision 1.29) -\pgf@path@lastx=\dimen195 -\pgf@path@lasty=\dimen196 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcorepathusage -.code.tex -File: pgfcorepathusage.code.tex 2013/12/13 (rcs-revision 1.23) -\pgf@shorten@end@additional=\dimen197 -\pgf@shorten@start@additional=\dimen198 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcorescopes.co -de.tex -File: pgfcorescopes.code.tex 2013/10/09 (rcs-revision 1.44) -\pgfpic=\box56 -\pgf@hbox=\box57 -\pgf@layerbox@main=\box58 -\pgf@picture@serial@count=\count178 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcoregraphicst -ate.code.tex -File: pgfcoregraphicstate.code.tex 2013/09/19 (rcs-revision 1.11) -\pgflinewidth=\dimen199 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcoretransform -ations.code.tex -File: pgfcoretransformations.code.tex 2013/10/10 (rcs-revision 1.17) -\pgf@pt@x=\dimen200 -\pgf@pt@y=\dimen201 -\pgf@pt@temp=\dimen202 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcorequick.cod -e.tex -File: pgfcorequick.code.tex 2008/10/09 (rcs-revision 1.3) -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcoreobjects.c -ode.tex -File: pgfcoreobjects.code.tex 2006/10/11 (rcs-revision 1.2) -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcorepathproce -ssing.code.tex -File: pgfcorepathprocessing.code.tex 2013/09/09 (rcs-revision 1.9) -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcorearrows.co -de.tex -File: pgfcorearrows.code.tex 2013/11/07 (rcs-revision 1.40) -\pgfarrowsep=\dimen203 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcoreshade.cod -e.tex -File: pgfcoreshade.code.tex 2013/07/15 (rcs-revision 1.15) -\pgf@max=\dimen204 -\pgf@sys@shading@range@num=\count179 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcoreimage.cod -e.tex -File: pgfcoreimage.code.tex 2013/07/15 (rcs-revision 1.18) - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcoreexternal. -code.tex -File: pgfcoreexternal.code.tex 2013/07/15 (rcs-revision 1.20) -\pgfexternal@startupbox=\box59 -)) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcorelayers.co -de.tex -File: pgfcorelayers.code.tex 2013/07/18 (rcs-revision 1.7) -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcoretranspare -ncy.code.tex -File: pgfcoretransparency.code.tex 2013/09/30 (rcs-revision 1.5) -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/basiclayer/pgfcorepatterns. -code.tex -File: pgfcorepatterns.code.tex 2013/11/07 (rcs-revision 1.5) -))) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/modules/pgfmoduleshapes.cod -e.tex -File: pgfmoduleshapes.code.tex 2013/10/31 (rcs-revision 1.34) -\pgfnodeparttextbox=\box60 -) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/modules/pgfmoduleplot.code. -tex -File: pgfmoduleplot.code.tex 2013/07/31 (rcs-revision 1.12) -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/compatibility/pgfcomp-version --0-65.sty -Package: pgfcomp-version-0-65 2007/07/03 v3.0.0 (rcs-revision 1.7) -\pgf@nodesepstart=\dimen205 -\pgf@nodesepend=\dimen206 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/compatibility/pgfcomp-version --1-18.sty -Package: pgfcomp-version-1-18 2007/07/23 v3.0.0 (rcs-revision 1.1) -)) -(/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/utilities/pgffor.sty -(/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/utilities/pgfkeys.sty -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/utilities/pgfkeys.code.tex) -) (/usr/local/texlive/2015/texmf-dist/tex/latex/pgf/math/pgfmath.sty -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmath.code.tex)) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/utilities/pgffor.code.tex -Package: pgffor 2013/12/13 v3.0.0 (rcs-revision 1.25) - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/math/pgfmath.code.tex) -\pgffor@iter=\dimen207 -\pgffor@skip=\dimen208 -\pgffor@stack=\toks44 -\pgffor@toks=\toks45 -)) -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/frontendlayer/tikz/tikz.cod -e.tex -Package: tikz 2013/12/13 v3.0.0 (rcs-revision 1.142) - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/libraries/pgflibraryplothan -dlers.code.tex -File: pgflibraryplothandlers.code.tex 2013/08/31 v3.0.0 (rcs-revision 1.20) -\pgf@plot@mark@count=\count180 -\pgfplotmarksize=\dimen209 -) -\tikz@lastx=\dimen210 -\tikz@lasty=\dimen211 -\tikz@lastxsaved=\dimen212 -\tikz@lastysaved=\dimen213 -\tikzleveldistance=\dimen214 -\tikzsiblingdistance=\dimen215 -\tikz@figbox=\box61 -\tikz@figbox@bg=\box62 -\tikz@tempbox=\box63 -\tikz@tempbox@bg=\box64 -\tikztreelevel=\count181 -\tikznumberofchildren=\count182 -\tikznumberofcurrentchild=\count183 -\tikz@fig@count=\count184 - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/modules/pgfmodulematrix.cod -e.tex -File: pgfmodulematrix.code.tex 2013/09/17 (rcs-revision 1.8) -\pgfmatrixcurrentrow=\count185 -\pgfmatrixcurrentcolumn=\count186 -\pgf@matrix@numberofcolumns=\count187 -) -\tikz@expandcount=\count188 - -(/usr/local/texlive/2015/texmf-dist/tex/generic/pgf/frontendlayer/tikz/librarie -s/tikzlibrarytopaths.code.tex -File: tikzlibrarytopaths.code.tex 2008/06/17 v3.0.0 (rcs-revision 1.2) -))) -(/usr/local/texlive/2015/texmf-dist/tex/latex/mdframed/md-frame-1.mdf -File: md-frame-1.mdf 2013/07/01\ 1.9b: md-frame-1 -) -\mdf@frametitlebox=\box65 -\mdf@footnotebox=\box66 -\mdf@splitbox@one=\box67 -\mdf@splitbox@two=\box68 -\mdf@splitbox@save=\box69 -\mdfsplitboxwidth=\skip113 -\mdfsplitboxtotalwidth=\skip114 -\mdfsplitboxheight=\skip115 -\mdfsplitboxdepth=\skip116 -\mdfsplitboxtotalheight=\skip117 -\mdfframetitleboxwidth=\skip118 -\mdfframetitleboxtotalwidth=\skip119 -\mdfframetitleboxheight=\skip120 -\mdfframetitleboxdepth=\skip121 -\mdfframetitleboxtotalheight=\skip122 -\mdffootnoteboxwidth=\skip123 -\mdffootnoteboxtotalwidth=\skip124 -\mdffootnoteboxheight=\skip125 -\mdffootnoteboxdepth=\skip126 -\mdffootnoteboxtotalheight=\skip127 -\mdftotallinewidth=\skip128 -\mdfboundingboxwidth=\skip129 -\mdfboundingboxtotalwidth=\skip130 -\mdfboundingboxheight=\skip131 -\mdfboundingboxdepth=\skip132 -\mdfboundingboxtotalheight=\skip133 -\mdf@freevspace@length=\skip134 -\mdf@horizontalwidthofbox@length=\skip135 -\mdf@verticalmarginwhole@length=\skip136 -\mdf@horizontalspaceofbox=\skip137 -\mdfsubtitleheight=\skip138 -\mdfsubsubtitleheight=\skip139 -\c@mdfcountframes=\count189 - -****** mdframed patching \endmdf@trivlist - -****** -- success****** - -................................................. -. LaTeX info: "xparse/define-command" -. -. Defining command \newmdtheoremenv with sig. 'O{} m o m o ' on line 601. -................................................. -................................................. -. LaTeX info: "xparse/define-command" -. -. Defining command \mdtheorem with sig. ' O{} m o m o ' on line 701. -................................................. -\mdf@envdepth=\count190 -\c@mdf@env@i=\count191 -\c@mdf@env@ii=\count192 -\c@mdf@zref@counter=\count193 -Package zref Info: New property: mdf@pagevalue on input line 895. -) -\@indexfile=\write7 -\openout7 = `Regression.idx'. - - -Writing index file Regression.idx -(/usr/local/texlive/2015/texmf-dist/tex/latex/idxlayout/idxlayout.sty -Package: idxlayout 2012/03/30 v0.4d Configurable index layout - -(/usr/local/texlive/2015/texmf-dist/tex/latex/tools/multicol.sty -Package: multicol 2015/03/31 v1.8m multicolumn formatting (FMi) -\c@tracingmulticols=\count194 -\mult@box=\box70 -\multicol@leftmargin=\dimen216 -\c@unbalance=\count195 -\c@collectmore=\count196 -\doublecol@number=\count197 -\multicoltolerance=\count198 -\multicolpretolerance=\count199 -\full@width=\dimen217 -\page@free=\dimen218 -\premulticols=\dimen219 -\postmulticols=\dimen220 -\multicolsep=\skip140 -\multicolbaselineskip=\skip141 -\partial@page=\box71 -\last@line=\box72 -\maxbalancingoverflow=\dimen221 -\mult@rightbox=\box73 -\mult@grightbox=\box74 -\mult@gfirstbox=\box75 -\mult@firstbox=\box76 -\@tempa=\box77 -\@tempa=\box78 -\@tempa=\box79 -\@tempa=\box80 -\@tempa=\box81 -\@tempa=\box82 -\@tempa=\box83 -\@tempa=\box84 -\@tempa=\box85 -\@tempa=\box86 -\@tempa=\box87 -\@tempa=\box88 -\@tempa=\box89 -\@tempa=\box90 -\@tempa=\box91 -\@tempa=\box92 -\@tempa=\box93 -\c@columnbadness=\count200 -\c@finalcolumnbadness=\count201 -\last@try=\dimen222 -\multicolovershoot=\dimen223 -\multicolundershoot=\dimen224 -\mult@nat@firstbox=\box94 -\colbreak@box=\box95 -\mc@col@check@num=\count202 -) -\c@idxcols=\count203 -\indexcolsep=\skip142 -\indexrule=\skip143 -\ila@indentunit=\skip144 -\ila@initsep=\skip145 -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/tocbibind/tocbibind.sty -Package: tocbibind 2010/10/13 v1.5k extra ToC listings -Package tocbibind Info: The document has section divisions on input line 50. - - -Package tocbibind Note: Using section or other style headings. - -) (/usr/local/texlive/2015/texmf-dist/tex/latex/ms/ragged2e.sty -Package: ragged2e 2009/05/21 v2.1 ragged2e Package (MS) - -(/usr/local/texlive/2015/texmf-dist/tex/latex/ms/everysel.sty -Package: everysel 2011/10/28 v1.2 EverySelectfont Package (MS) -) -\CenteringLeftskip=\skip146 -\RaggedLeftLeftskip=\skip147 -\RaggedRightLeftskip=\skip148 -\CenteringRightskip=\skip149 -\RaggedLeftRightskip=\skip150 -\RaggedRightRightskip=\skip151 -\CenteringParfillskip=\skip152 -\RaggedLeftParfillskip=\skip153 -\RaggedRightParfillskip=\skip154 -\JustifyingParfillskip=\skip155 -\CenteringParindent=\skip156 -\RaggedLeftParindent=\skip157 -\RaggedRightParindent=\skip158 -\JustifyingParindent=\skip159 -) -(./Regression.aux) -\openout1 = `Regression.aux'. - -LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 98. -LaTeX Font Info: ... okay on input line 98. -LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 98. -LaTeX Font Info: ... okay on input line 98. -LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 98. -LaTeX Font Info: ... okay on input line 98. -LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 98. -LaTeX Font Info: ... okay on input line 98. -LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 98. -LaTeX Font Info: ... okay on input line 98. -LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 98. -LaTeX Font Info: ... okay on input line 98. -LaTeX Font Info: Checking defaults for PD1/pdf/m/n on input line 98. -LaTeX Font Info: ... okay on input line 98. -LaTeX Font Info: Try loading font information for T1+lmr on input line 98. - (/usr/local/texlive/2015/texmf-dist/tex/latex/lm/t1lmr.fd -File: t1lmr.fd 2009/10/30 v1.6 Font defs for Latin Modern -) -(/usr/local/texlive/2015/texmf-dist/tex/context/base/supp-pdf.mkii -[Loading MPS to PDF converter (version 2006.09.02).] -\scratchcounter=\count204 -\scratchdimen=\dimen225 -\scratchbox=\box96 -\nofMPsegments=\count205 -\nofMParguments=\count206 -\everyMPshowfont=\toks46 -\MPscratchCnt=\count207 -\MPscratchDim=\dimen226 -\MPnumerator=\count208 -\makeMPintoPDFobject=\count209 -\everyMPtoPDFconversion=\toks47 -) -LaTeX Info: Redefining \microtypecontext on input line 98. -Package microtype Info: Generating PDF output. -Package microtype Info: Character protrusion enabled (level 2). -Package microtype Info: Using default protrusion set `alltext'. -Package microtype Info: Automatic font expansion enabled (level 2), -(microtype) stretch: 20, shrink: 20, step: 1, non-selected. -Package microtype Info: Using default expansion set `basictext'. -Package microtype Info: No adjustment of tracking. -Package microtype Info: No adjustment of interword spacing. -Package microtype Info: No adjustment of character kerning. - (/usr/local/texlive/2015/texmf-dist/tex/latex/microtype/mt-cmr.cfg -File: mt-cmr.cfg 2013/05/19 v2.2 microtype config. file: Computer Modern Roman -(RS) -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/oberdiek/epstopdf-base.sty -Package: epstopdf-base 2010/02/09 v2.5 Base part for package epstopdf - -(/usr/local/texlive/2015/texmf-dist/tex/latex/oberdiek/grfext.sty -Package: grfext 2010/08/19 v1.1 Manage graphics extensions (HO) -) -Package grfext Info: Graphics extension search list: -(grfext) [.png,.pdf,.jpg,.mps,.jpeg,.jbig2,.jb2,.PNG,.PDF,.JPG,.JPE -G,.JBIG2,.JB2,.eps] -(grfext) \AppendGraphicsExtensions on input line 452. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/latexconfig/epstopdf-sys.cfg -File: epstopdf-sys.cfg 2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Liv -e -)) -(/usr/local/texlive/2015/texmf-dist/tex/latex/ucs/ucsencs.def -File: ucsencs.def 2011/01/21 Fixes to fontencodings LGR, T3 -) -\AtBeginShipoutBox=\box97 -Package hyperref Info: Link coloring ON on input line 98. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/hyperref/nameref.sty -Package: nameref 2012/10/27 v2.43 Cross-referencing by name of section - -(/usr/local/texlive/2015/texmf-dist/tex/generic/oberdiek/gettitlestring.sty -Package: gettitlestring 2010/12/03 v1.4 Cleanup title references (HO) -) -\c@section@level=\count210 -) -LaTeX Info: Redefining \ref on input line 98. -LaTeX Info: Redefining \pageref on input line 98. -LaTeX Info: Redefining \nameref on input line 98. - -(./Regression.out) (./Regression.out) -\@outlinefile=\write8 -\openout8 = `Regression.out'. - - ABD: EveryShipout initializing macros -ABD: EverySelectfont initializing macros -LaTeX Info: Redefining \selectfont on input line 98. -LaTeX Font Info: Try loading font information for OT1+lmr on input line 124. - - -(/usr/local/texlive/2015/texmf-dist/tex/latex/lm/ot1lmr.fd -File: ot1lmr.fd 2009/10/30 v1.6 Font defs for Latin Modern -) -LaTeX Font Info: Try loading font information for OML+lmm on input line 124. - - -(/usr/local/texlive/2015/texmf-dist/tex/latex/lm/omllmm.fd -File: omllmm.fd 2009/10/30 v1.6 Font defs for Latin Modern -) -LaTeX Font Info: Try loading font information for OMS+lmsy on input line 124 -. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/lm/omslmsy.fd -File: omslmsy.fd 2009/10/30 v1.6 Font defs for Latin Modern -) -LaTeX Font Info: Try loading font information for OMX+lmex on input line 124 -. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/lm/omxlmex.fd -File: omxlmex.fd 2009/10/30 v1.6 Font defs for Latin Modern -) -LaTeX Font Info: External font `lmex10' loaded for size -(Font) <10> on input line 124. -LaTeX Font Info: External font `lmex10' loaded for size -(Font) <7> on input line 124. -LaTeX Font Info: External font `lmex10' loaded for size -(Font) <5> on input line 124. -LaTeX Font Info: Try loading font information for U+msa on input line 124. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/amsfonts/umsa.fd -File: umsa.fd 2013/01/14 v3.01 AMS symbols A -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/microtype/mt-msa.cfg -File: mt-msa.cfg 2006/02/04 v1.1 microtype config. file: AMS symbols (a) (RS) -) -LaTeX Font Info: Try loading font information for U+msb on input line 124. - -(/usr/local/texlive/2015/texmf-dist/tex/latex/amsfonts/umsb.fd -File: umsb.fd 2013/01/14 v3.01 AMS symbols B -) -(/usr/local/texlive/2015/texmf-dist/tex/latex/microtype/mt-msb.cfg -File: mt-msb.cfg 2005/06/01 v1.0 microtype config. file: AMS symbols (b) (RS) -) -LaTeX Font Info: External font `lmex10' loaded for size -(Font) <9> on input line 129. -LaTeX Font Info: External font `lmex10' loaded for size -(Font) <6> on input line 129. -LaTeX Font Info: Try loading font information for OMS+lmr on input line 149. - - -(/usr/local/texlive/2015/texmf-dist/tex/latex/lm/omslmr.fd -File: omslmr.fd 2009/10/30 v1.6 Font defs for Latin Modern -) -LaTeX Font Info: Font shape `OMS/lmr/m/n' in size <10> not available -(Font) Font shape `OMS/lmsy/m/n' tried instead on input line 149. -LaTeX Font Info: Font shape `OMS/lmr/m/n' in size <8> not available -(Font) Font shape `OMS/lmsy/m/n' tried instead on input line 181. - [1 - -{/usr/local/texlive/2015/texmf-var/fonts/map/pdftex/updmap/pdftex.map}] -Overfull \hbox (37.20496pt too wide) in paragraph at lines 188--189 -[]$\OML/lmm/m/it/10 p$ \T1/lmr/m/n/10 (-20) so-called ex-plana-tory (in-de-pen- -dent or pre-dic-tor) vari-ables $\OML/cmm/b/it/10 x[] \OT1/lmr/m/n/10 (-20) = [ -\OML/lmm/m/it/10 x[]; x[]; [] ; x[]\OT1/lmr/m/n/10 (-20) ]$ - [] - -[2] [3] [4] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/51639A41B11E5FE7D4CD027BA48FB6C64B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.481 \end{minted} - -? s -OK, entering \scrollmode... -[5] [6] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/4C68C697EB414B135747B9ECA18C3B5B4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.637 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/439DCAB036A38F6389948C8DF1465C424B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.642 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[7] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/0A3C1B39ACFAF4BAB627404CB6156A144B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.658 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -! Missing $ inserted. - - $ -l.663 ...in connection with the functionality of _ - Scikit_Learn_ in the intro... -I've inserted a begin-math/end-math symbol since I think -you left one out. Proceed, with fingers crossed. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/F5688422A51FDCF3C06A3FF7EF8F9E6E4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.668 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/FE87C84792E25A9D98329B989214E79F4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.672 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -! Missing $ inserted. - - $ -l.673 - -I've inserted a begin-math/end-math symbol since I think -you left one out. Proceed, with fingers crossed. - - -Overfull \hbox (64.00754pt too wide) in paragraph at lines 663--673 -\T1/lmr/m/n/10 (-20) tion with the func-tion-al-ity of $[]\OML/lmm/m/it/10 ciki -t[]earn[]ntheintroductoryslides:Sincewearenotusing[]cikit \OMS/lmsy/m/n/10 ^^@ - [] - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/F9FF5FEA9F501D7189D0F820FC8D1D3D4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.681 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/2702C77D52D3F655EDD2BB83D8F1240B4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.687 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -LaTeX Font Info: External font `lmex10' loaded for size -(Font) <12> on input line 694. -LaTeX Font Info: External font `lmex10' loaded for size -(Font) <8> on input line 694. - -Overfull \hbox (8.74574pt too wide) detected at line 728 -[] \OT1/lmr/m/n/10 = [] [] = 0\OML/lmm/m/it/10 ; - [] - - -Overfull \hbox (9.06128pt too wide) detected at line 732 -[] \OT1/lmr/m/n/10 = \OMS/lmsy/m/n/10 ^^@[] [] \OT1/lmr/m/n/10 = 0\OML/lmm/m/it -/10 ; - [] - -[8] [9] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/E81889C7775BD173862927052713983D4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.968 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[10] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/31D43D24D5F9D55728C4E563E0E557924B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.1057 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/F6068C18D7EFD701D08693F8BD52B4664B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.1125 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[11] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/9CC2E80F086A0B9D080182D504A931C14B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.1165 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/4C6F7D24872AF7644FF40FC87BFFAB2B4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.1197 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/C8DBC01C383B0800E51E0923C05691E04B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.1203 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[12] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/E06035EDB37DBFD5697CD9DD1C5CA4A34B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.1244 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/363FA9AE05CC4E390538E08524572CF34B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.1248 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/367BFC34E39C7EA712AF1384CAA96F674B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.1254 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/09054641A8F49E0FADA410EE6C9BC1BA4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.1268 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[13] - -! LaTeX Error: Bad math environment delimiter. - -See the LaTeX manual or LaTeX Companion for explanation. -Type H for immediate help. - ... - -l.1353 \[ - -Your command was ignored. -Type I to replace it with another command, -or to continue without it. - -! Missing \endgroup inserted. - - \endgroup -l.1355 \] - -I've inserted something that you may have forgotten. -(See the above.) -With luck, this will get me unwedged. But if you -really didn't forget anything, try typing `2' now; then -my insertion and my current dilemma will both disappear. - -! Missing \endgroup inserted. - - \endgroup -l.1355 \] - -I've inserted something that you may have forgotten. -(See the above.) -With luck, this will get me unwedged. But if you -really didn't forget anything, try typing `2' now; then -my insertion and my current dilemma will both disappear. - - -Overfull \hbox (63.72496pt too wide) detected at line 1355 -\OT1/lmr/m/n/10 (\OML/lmm/m/it/10 ^^U[]; \OML/cmm/b/it/10 u[]\OT1/lmr/m/n/10 )\ -OML/lmm/m/it/10 ; [] ; \OT1/lmr/m/n/10 (\OML/lmm/m/it/10 ^^U[]; \OML/cmm/b/it/1 -0 u[]\OT1/lmr/m/n/10 )\OML/lmm/m/it/10 ; andtheeigenvaluesaregivenbythediagonal -matrix\OT1/cmr/bx/n/10 ^^F \OT1/lmr/m/n/10 = [](\OML/lmm/m/it/10 ^^U[]; [] ; ^^ -U[]\OT1/lmr/m/n/10 )\OML/lmm/m/it/10 : - [] - -[14] - -! LaTeX Error: \begin{bmatrix} on input line 1407 ended by \end{matrix}. - -See the LaTeX manual or LaTeX Companion for explanation. -Type H for immediate help. - ... - -l.1407 ...x} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix} - =\frac{1}{3}\begin{bmatrix... - -Your command was ignored. -Type I to replace it with another command, -or to continue without it. - -! Missing \right. inserted. - - \right . -l.1407 ...x} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix} - =\frac{1}{3}\begin{bmatrix... -I've inserted something that you may have forgotten. -(See the above.) -With luck, this will get me unwedged. But if you -really didn't forget anything, try typing `2' now; then -my insertion and my current dilemma will both disappear. - -[15] [16] [17] [18] [19] -(/usr/local/texlive/2015/texmf-dist/tex/latex/ucs/data/uni-32.def -File: uni-32.def 2013/05/13 UCS: Unicode data U+2000..U+20FF -) [20] -[21] -Overfull \hbox (12.18277pt too wide) in paragraph at lines 1886--1888 - [][] \T1/lmr/m/n/10 (-20) If $\OML/lmm/m/it/10 X[]$ \T1/lmr/m/n/10 (-20) and $ -\OML/lmm/m/it/10 X[]$ \T1/lmr/m/n/10 (-20) are in-de-pen-dent, we get $\OMS/lms -y/m/n/10 h\OML/lmm/m/it/10 x[]x[]\OMS/lmsy/m/n/10 i \OT1/lmr/m/n/10 (-20) = \OM -S/lmsy/m/n/10 h\OML/lmm/m/it/10 x[]\OMS/lmsy/m/n/10 ih\OML/lmm/m/it/10 x[]\OMS/ -lmsy/m/n/10 i$\T1/lmr/m/n/10 (-20) , re-sult-ing in $[]\OT1/lmr/m/n/10 (-20) (\ -OML/lmm/m/it/10 X[]; X[]\OT1/lmr/m/n/10 (-20) ) = - [] - -[22] [23] [24] [25] [26] [27] [28] [29] [30] [31] [32] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/A7435FEC44C0E9C1E9660C02CDC74B3F4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.2638 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[33] -Overfull \hbox (23.70952pt too wide) in paragraph at lines 2724--2725 -[]\T1/lmr/m/n/10 (-20) Draw with re-place-ment $\OML/lmm/m/it/10 n$ \T1/lmr/m/n -/10 (-20) num-bers for the ob-served vari-ables $\OML/cmm/b/it/10 x \OT1/lmr/m/ -n/10 (-20) = (\OML/lmm/m/it/10 x[]; x[]; [] ; x[]\OT1/lmr/m/n/10 (-20) )$\T1/l -mr/m/n/10 (-20) . - [] - -[34] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/16523CD54121DE1835E829B872835EA64B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.2805 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - - -Overfull \hbox (15.6617pt too wide) in paragraph at lines 2809--2809 -[][]\T1/lmr/bx/n/12 Code Ex-am-ple for Cross-validation and $\OML/lmm/m/it/12 k -$\T1/lmr/bx/n/12 -fold Cross-validation - [] - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/5A860BD7323291C7CF7221BB9B86BDC74B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.2903 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[35] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/457F2C4C88437DDFAF88B1D28783CF034B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3022 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/066BCC1A504ED48C98D58B2EC6A448284B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3078 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[36] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/5D2065327E88AF636A043C8526ED982B4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3190 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/B0F453236926744E43E08A3FC3D889CE4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3234 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/BFFA2954B53E806314EE31A7A4153BE34B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3272 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/F0C6E7177EB3BF181C2BCDCF6C126D174B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3278 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[37] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/679F13D40F197D86A49DDBAE2064874A4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3282 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/ECE8CFF2AC201FE83D423B89AB24D84D4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3293 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/90854007E426D557D1191356516A553B4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3321 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - - -Overfull \hbox (2.88571pt too wide) in paragraph at lines 3326--3327 -\T1/lmr/m/n/10 (-20) In the \T1/lmr/bx/n/10 Least Ab-so-lute Shrink-age and Se- -lec-tion Op-er-a-tor \T1/lmr/m/n/10 (-20) (LASSO)-method - [] - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/D10574B3CE6341E3B1CE27A555FC959C4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3346 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/207A7B5C5A05397AD9CC324488E0F0A34B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3397 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/0FE2839ED408ED62CECC4C3D9FE2DDE84B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3446 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/EAD510BC3ABCC6143355164B81A3C2ED4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3463 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[38] [39] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/EAD510BC3ABCC6143355164B81A3C2ED4B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3526 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - -[40] -\openout3 = `Regression.pyg'. - -runsystem(pygmentize -l python -f latex -F tokenmerge -P style=default -P comma -ndprefix=PYGdefault -P style=default -P commandprefix=PYGdefault -P mathescape= -True -o "_minted-Regression/795F82986CD7DD6E2E776380A1AFB2624B967B05670D715D94F -4392BD3176A49.pygtex" "Regression.pyg" )...executed. - - - -! Package minted Error: Missing Pygments output; \inputminted was -probably given a file that does not exist--otherwise, you may need -the outputdir package option, or may be using an incompatible build tool. - -See the minted package documentation for explanation. -Type H for immediate help. - ... - -l.3630 \end{minted} - -This could be caused by using -output-directory or -aux-directory -without setting minted's outputdir, or by using a build tool that -changes paths in ways minted cannot detect. - - -Overfull \hbox (4.59245pt too wide) in paragraph at lines 3633--3637 -[]\T1/lmr/m/n/10 (-20) We will thus again gen-er-ate our own dataset for a func --tion $[]\OT1/lmr/m/n/10 (-20) (\OML/lmm/m/it/10 x; y\OT1/lmr/m/n/10 (-20) )$ - [] - -[41] -runsystem(rm "Regression.pyg")...executed. - - [42] -Package atveryend Info: Empty hook `BeforeClearDocument' on input line 3672. -Package atveryend Info: Empty hook `AfterLastShipout' on input line 3672. - (./Regression.aux) -Package atveryend Info: Executing hook `AtVeryEndDocument' on input line 3672. - - - *File List* - article.cls 2014/09/29 v1.4h Standard LaTeX document class - size10.clo 2014/09/29 v1.4h Standard LaTeX file (size option) - relsize.sty 2013/03/29 ver 4.1 - makeidx.sty 2014/09/29 v1.0m Standard LaTeX package - color.sty 1999/02/16 - color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive - pdftex.def 2011/05/27 v0.06d Graphics/color for pdfTeX -infwarerr.sty 2010/04/08 v1.3 Providing info/warning/error messages (HO) - ltxcmds.sty 2011/11/09 v1.22 LaTeX kernel commands for general use (HO) -setspace.sty 2011/12/19 v6.7a set line spacing - amsmath.sty 2013/01/14 v2.14 AMS math features - amstext.sty 2000/06/29 v2.01 - amsgen.sty 1999/11/30 v2.0 - amsbsy.sty 1999/11/29 v1.2d - amsopn.sty 1999/12/14 v2.01 operator names -amsfonts.sty 2013/01/14 v3.01 Basic AMSFonts support - amssymb.sty 2013/01/14 v3.01 AMS font symbols - xcolor.sty 2007/01/21 v2.11 LaTeX color extensions (UK) - color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive -colortbl.sty 2012/02/13 v1.0a Color table columns (DPC) - array.sty 2014/10/28 v2.4c Tabular extension package (FMi) - bm.sty 2014/10/28 v1.1c Bold Symbol Support (DPC/FMi) - ltablex.sty 2014/08/13 v1.1 Modified tabularx -longtable.sty 2014/10/28 v4.11 Multi-page Table package (DPC) -tabularx.sty 2014/10/28 v2.10 `tabularx' package (DPC) -microtype.sty 2013/05/23 v2.5a Micro-typographical refinements (RS) - keyval.sty 2014/10/28 v1.15 key=value parser (DPC) -microtype-pdftex.def 2013/05/23 v2.5a Definitions specific to pdftex (RS) -microtype.cfg 2013/05/23 v2.5a microtype main configuration file (RS) -graphicx.sty 2014/10/28 v1.0g Enhanced LaTeX Graphics (DPC,SPQR) -graphics.sty 2014/10/28 v1.0p Standard LaTeX Graphics (DPC,SPQR) - trig.sty 1999/03/16 v1.09 sin cos tan (DPC) -graphics.cfg 2010/04/23 v1.9 graphics configuration of TeX Live -fancyvrb.sty 2008/02/07 - minted.sty 2015/01/31 v2.0 Yet another Pygments shim for LaTeX -kvoptions.sty 2011/06/30 v3.11 Key value format for package options (HO) -kvsetkeys.sty 2012/04/25 v1.16 Key value parser (HO) -etexcmds.sty 2011/02/16 v1.5 Avoid name clashes with e-TeX commands (HO) -ifluatex.sty 2010/03/01 v1.3 Provides the ifluatex switch (HO) - float.sty 2001/11/08 v1.3d Float enhancements (AL) - ifthen.sty 2014/09/29 v1.1c Standard LaTeX ifthen package (DPC) - calc.sty 2014/10/28 v4.3 Infix arithmetic (KKT,FJ) -ifplatform.sty 2010/10/22 v0.4 Testing for the operating system -pdftexcmds.sty 2011/11/29 v0.20 Utility functions of pdfTeX for LuaTeX (HO) - ifpdf.sty 2011/01/30 v2.3 Provides the ifpdf switch (HO) -catchfile.sty 2011/03/01 v1.6 Catch the contents of a file (HO) -Regression.w18 -etoolbox.sty 2015/05/04 v2.2 e-TeX tools for LaTeX (JAW) - xstring.sty 2013/10/13 v1.7c String manipulations (C Tellechea) - lineno.sty 2005/11/02 line numbers on paragraphs v4.41 -_minted-Regression/default.pygstyle - fontenc.sty - t1enc.def 2005/09/27 v1.99g Standard LaTeX file - ucs.sty 2013/05/11 v2.2 UCS: Unicode input support -uni-global.def 2013/05/13 UCS: Unicode global data -inputenc.sty 2015/03/17 v1.2c Input encoding file - utf8x.def 2004/10/17 UCS: Input encoding UTF-8 - lmodern.sty 2009/10/30 v1.6 Latin Modern Fonts -hyperref.sty 2012/11/06 v6.83m Hypertext links for LaTeX -hobsub-hyperref.sty 2012/05/28 v1.13 Bundle oberdiek, subset hyperref (HO) -hobsub-generic.sty 2012/05/28 v1.13 Bundle oberdiek, subset generic (HO) - hobsub.sty 2012/05/28 v1.13 Construct package bundles (HO) - ifvtex.sty 2010/03/01 v1.5 Detect VTeX and its facilities (HO) - intcalc.sty 2007/09/27 v1.1 Expandable calculations with integers (HO) -kvdefinekeys.sty 2011/04/07 v1.3 Define keys (HO) -pdfescape.sty 2011/11/25 v1.13 Implements pdfTeX's escape features (HO) -bigintcalc.sty 2012/04/08 v1.3 Expandable calculations on big integers (HO) - bitset.sty 2011/01/30 v1.1 Handle bit-vector datatype (HO) -uniquecounter.sty 2011/01/30 v1.2 Provide unlimited unique counter (HO) -letltxmacro.sty 2010/09/02 v1.4 Let assignment for LaTeX macros (HO) - hopatch.sty 2012/05/28 v1.2 Wrapper for package hooks (HO) -xcolor-patch.sty 2011/01/30 xcolor patch -atveryend.sty 2011/06/30 v1.8 Hooks at the very end of document (HO) -atbegshi.sty 2011/10/05 v1.16 At begin shipout hook (HO) -refcount.sty 2011/10/16 v3.4 Data extraction from label references (HO) - hycolor.sty 2011/01/30 v1.7 Color options for hyperref/bookmark (HO) - ifxetex.sty 2010/09/12 v0.6 Provides ifxetex conditional - auxhook.sty 2011/03/04 v1.3 Hooks for auxiliary files (HO) - pd1enc.def 2012/11/06 v6.83m Hyperref: PDFDocEncoding definition (HO) -hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive - url.sty 2013/09/16 ver 3.4 Verb mode for urls, etc. - hpdftex.def 2012/11/06 v6.83m Hyperref driver for pdfTeX -rerunfilecheck.sty 2011/04/15 v1.7 Rerun checks for auxiliary files (HO) -fancyhdr.sty -mdframed.sty 2013/07/01 1.9b: mdframed - xparse.sty 2014/11/25 v5471 L3 Experimental document command parser - expl3.sty 2015/03/01 v5547 L3 programming layer (loader) -expl3-code.tex 2015/03/01 v5547 L3 programming layer -l3unicode-data.def 2015/03/01 v5544 L3 Unicode data -l3pdfmode.def 2015/03/01 v5544 L3 Experimental driver: PDF mode -zref-abspage.sty 2012/04/04 v2.24 Module abspage for zref (HO) -zref-base.sty 2012/04/04 v2.24 Module base for zref (HO) -needspace.sty 2010/09/12 v1.3d reserve vertical space - tikz.sty 2013/12/13 v3.0.0 (rcs-revision 1.142) - pgf.sty 2013/12/18 v3.0.0 (rcs-revision 1.14) - pgfrcs.sty 2013/12/20 v3.0.0 (rcs-revision 1.28) -everyshi.sty 2001/05/15 v3.00 EveryShipout Package (MS) - pgfrcs.code.tex - pgfcore.sty 2010/04/11 v3.0.0 (rcs-revision 1.7) - pgfsys.sty 2013/11/30 v3.0.0 (rcs-revision 1.47) - pgfsys.code.tex -pgfsyssoftpath.code.tex 2013/09/09 (rcs-revision 1.9) -pgfsysprotocol.code.tex 2006/10/16 (rcs-revision 1.4) - pgfcore.code.tex -pgfcomp-version-0-65.sty 2007/07/03 v3.0.0 (rcs-revision 1.7) -pgfcomp-version-1-18.sty 2007/07/23 v3.0.0 (rcs-revision 1.1) - pgffor.sty 2013/12/13 v3.0.0 (rcs-revision 1.25) - pgfkeys.sty - pgfkeys.code.tex - pgfmath.sty - pgfmath.code.tex - pgffor.code.tex - tikz.code.tex -md-frame-1.mdf 2013/07/01\ 1.9b: md-frame-1 -idxlayout.sty 2012/03/30 v0.4d Configurable index layout -multicol.sty 2015/03/31 v1.8m multicolumn formatting (FMi) -tocbibind.sty 2010/10/13 v1.5k extra ToC listings -ragged2e.sty 2009/05/21 v2.1 ragged2e Package (MS) -everysel.sty 2011/10/28 v1.2 EverySelectfont Package (MS) - t1lmr.fd 2009/10/30 v1.6 Font defs for Latin Modern -supp-pdf.mkii - mt-cmr.cfg 2013/05/19 v2.2 microtype config. file: Computer Modern Roman ( -RS) -epstopdf-base.sty 2010/02/09 v2.5 Base part for package epstopdf - grfext.sty 2010/08/19 v1.1 Manage graphics extensions (HO) -epstopdf-sys.cfg 2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Live - ucsencs.def 2011/01/21 Fixes to fontencodings LGR, T3 - nameref.sty 2012/10/27 v2.43 Cross-referencing by name of section -gettitlestring.sty 2010/12/03 v1.4 Cleanup title references (HO) -Regression.out -Regression.out - ot1lmr.fd 2009/10/30 v1.6 Font defs for Latin Modern - omllmm.fd 2009/10/30 v1.6 Font defs for Latin Modern - omslmsy.fd 2009/10/30 v1.6 Font defs for Latin Modern - omxlmex.fd 2009/10/30 v1.6 Font defs for Latin Modern - umsa.fd 2013/01/14 v3.01 AMS symbols A - mt-msa.cfg 2006/02/04 v1.1 microtype config. file: AMS symbols (a) (RS) - umsb.fd 2013/01/14 v3.01 AMS symbols B - mt-msb.cfg 2005/06/01 v1.0 microtype config. file: AMS symbols (b) (RS) - omslmr.fd 2009/10/30 v1.6 Font defs for Latin Modern - uni-32.def 2013/05/13 UCS: Unicode data U+2000..U+20FF - *********** - -Package atveryend Info: Executing hook `AtEndAfterFileList' on input line 3672. - -Package rerunfilecheck Info: File `Regression.out' has not changed. -(rerunfilecheck) Checksum: D41D8CD98F00B204E9800998ECF8427E;0. - ) -Here is how much of TeX's memory you used: - 28066 strings out of 493089 - 535586 string characters out of 6134842 - 655626 words of memory out of 5000000 - 30575 multiletter control sequences out of 15000+600000 - 92488 words of font info for 170 fonts, out of 8000000 for 9000 - 1141 hyphenation exceptions out of 8191 - 67i,15n,64p,10395b,430s stack positions out of 5000i,500n,10000p,200000b,80000s -{/usr/local/texlive/2015/texmf-dist/fonts/enc/dvips/lm/lm-mathsy.enc}{/usr/lo -cal/texlive/2015/texmf-dist/fonts/enc/dvips/lm/lm-rm.enc}{/usr/local/texlive/20 -15/texmf-dist/fonts/enc/dvips/lm/lm-mathit.enc}{/usr/local/texlive/2015/texmf-d -ist/fonts/enc/dvips/lm/lm-mathex.enc}{/usr/local/texlive/2015/texmf-dist/fonts/ -enc/dvips/lm/lm-ec.enc} -Output written on Regression.pdf (42 pages, 459187 bytes). -PDF statistics: - 582 PDF objects out of 1000 (max. 8388607) - 508 compressed objects within 6 object streams - 247 named destinations out of 1000 (max. 500000) - 28685 words of extra memory for PDF output out of 29859 (max. 10000000) - diff --git a/doc/src/Regression/Regression.out b/doc/src/Regression/Regression.out deleted file mode 100644 index e69de29bb..000000000 diff --git a/doc/src/Regression/Regression.p.tex b/doc/src/Regression/Regression.p.tex deleted file mode 100644 index 9e331b7eb..000000000 --- a/doc/src/Regression/Regression.p.tex +++ /dev/null @@ -1,3703 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% -% #ifdef PTEX2TEX_EXPLANATION -%% -%% The file follows the ptex2tex extended LaTeX format, see -%% ptex2tex: http://code.google.com/p/ptex2tex/ -%% -%% Run -%% ptex2tex myfile -%% or -%% doconce ptex2tex myfile -%% -%% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex. -%% (The ptex2tex program: http://code.google.com/p/ptex2tex) -%% Many preprocess options can be added to ptex2tex or doconce ptex2tex -%% -%% ptex2tex -DMINTED myfile -%% doconce ptex2tex myfile envir=minted -%% -%% ptex2tex will typeset code environments according to a global or local -%% .ptex2tex.cfg configure file. doconce ptex2tex will typeset code -%% according to options on the command line (just type doconce ptex2tex to -%% see examples). If doconce ptex2tex has envir=minted, it enables the -%% minted style without needing -DMINTED. -% #endif - -% #define PREAMBLE - -% #ifdef PREAMBLE -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{ptex2tex} -% #ifdef MINTED -\usepackage{minted} -\usemintedstyle{default} -% #endif - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -\usepackage[framemethod=TikZ]{mdframed} - -% --- begin definitions of admonition environments --- - -% --- end of definitions of admonition environments --- - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE -% #endif - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Jul 22, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection{Why Linear Regression (aka Ordinary Least Squares and family)} - -Fitting a continuous function with linear parameterization in terms of the parameters $\bm{\beta}$. -\begin{itemize} -\item Method of choice for fitting a continuous function! - -\item Gives an excellent introduction to central Machine Learning features with \textbf{understandable pedagogical} links to other methods like \textbf{Neural Networks}, \textbf{Support Vector Machines} etc - -\item Analytical expression for the fitting parameters $\bm{\beta}$ - -\item Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more - -\item Analytical relation with probabilistic interpretations - -\item Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics - -\item Easy to code! And links well with classification problems and logistic regression and neural networks - -\item Allows for \textbf{easy} hands-on understanding of gradient descent methods - -\item and many more features -\end{itemize} - -\noindent -For more discussions of Ridge and Lasso regression, \href{{https://arxiv.org/abs/1509.09169}}{Wessel van Wieringen's} article is highly recommended. -Similarly, \href{{https://arxiv.org/abs/1803.08823}}{Mehta et al's article} is also recommended. - - -% !split -\subsection{Regression analysis, overarching aims} - -% --- begin paragraph admon --- -\paragraph{} - -Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\bm{x} =[x_0, x_1,\dots, x_{n-1}]^T$. -The first variable is called the \textbf{dependent}, the \textbf{outcome} or the \textbf{response} variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable. - -A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$, that is the conditional distribution for $\bm{y}$ with a given $\bm{x}$. The estimation of $p(\bm{y}\vert \bm{x})$ is made using a data set with -\begin{itemize} -\item $n$ cases $i = 0, 1, 2, \dots, n-1$ - -\item Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ - -\item $p$ so-called explanatory (independent or predictor) variables $\bm{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}]$ with $i = 0, 1, 2, \dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. -\end{itemize} - -\noindent - The goal of the regression analysis is to extract/exploit relationship between $\bm{y}$ and $\bm{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. -% --- end paragraph admon --- - - - -% !split -\subsection{Regression analysis, overarching aims II} - -% --- begin paragraph admon --- -\paragraph{} - - -Consider an experiment in which $p$ characteristics of $n$ samples are -measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix -$\mathbf{X}$. - -The matrix $\mathbf{X}$ is called the \emph{design -matrix}. Additional information of the samples is available in the -form of $\bm{y}$ (also as above). The variable $\bm{y}$ is -generally referred to as the \emph{response variable}. The aim of -regression analysis is to explain $\bm{y}$ in terms of -$\bm{X}$ through a functional relationship like $y_i = -f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of -$f(\cdot)$ is available, it is common to assume a linear relationship -between $\bm{X}$ and $\bm{y}$. This assumption gives rise to -the \emph{linear regression model} where $\bm{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T}$ are the \emph{regression parameters}. - -Linear regression gives us a set of analytical equations for the parameters $\beta_j$. -% --- end paragraph admon --- - - - - - -% !split -\subsection{Examples} - -% --- begin paragraph admon --- -\paragraph{} -In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$, -consider the model we discussed for describing nuclear binding energies. - -There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. -Assuming -\[ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, -\] -we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms. -This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a -$p\times n$ matrix $\bm{X}$. - -Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called \href{{https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub}}{credit card default data from Taiwan}. The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \times 30000$ -% --- end paragraph admon --- - - - - - - - -% !split -\subsection{General linear models} - -% --- begin paragraph admon --- -\paragraph{} -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\bm{y}=[y_0,y_1,\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\bm{x}=[x_0,x_1,\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. - -Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is -\[ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, -\] -where $\epsilon_i$ is the error in our approximation. -% --- end paragraph admon --- - - - - -% !split -\subsection{Rewriting the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} -For every set of values $y_i,x_i$ we have thus the corresponding set of equations -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -% --- end paragraph admon --- - - - - -% !split -\subsection{Rewriting the fitting procedure as a linear algebra problem, more details} - -% --- begin paragraph admon --- -\paragraph{} -Defining the vectors -\[ -\bm{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -\] -and -\[ -\bm{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -\] -and -\[ -\bm{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -\] -and the design matrix -\[ -\bm{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -\] -we can rewrite our equations as -\[ -\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. -\] -The above design matrix is called a \href{{https://en.wikipedia.org/wiki/Vandermonde_matrix}}{Vandermonde matrix}. -% --- end paragraph admon --- - - - - -% !split -\subsection{Generalizing the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} - -We are obviously not limited to the above polynomial expansions. We -could replace the various powers of $x$ with elements of Fourier -series or instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j -x_i)}$, or time series or other orthogonal functions. For every set -of values $y_i,x_i$ we can then generalize the equations to - -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} - -\textbf{Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!} -% --- end paragraph admon --- - - - - -% !split -\subsection{Generalizing the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} -We redefine in turn the matrix $\bm{X}$ as -\[ -\bm{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -\] -and without loss of generality we rewrite again our equations as -\[ -\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. -\] -The left-hand side of this equation is kwown. Our error vector $\bm{\epsilon}$ and the parameter vector $\bm{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? -% --- end paragraph admon --- - - - - -% !split -\subsection{Optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -We have defined the matrix $\bm{X}$ via the equations -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} - -As we noted above, we stayed with a system with the design matrix - $\bm{X}\in {\mathbb{R}}^{n\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define -our matrix as $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements. -% --- end paragraph admon --- - - - - -% !split -\subsection{Our model for the nuclear binding energies} - -In our \href{{https://compphysics.github.io/MachineLearningMSU/doc/pub/Introduction/html/Introduction.html}}{introductory notes} we looked at the so-called \href{{https://en.wikipedia.org/wiki/Semi-empirical_mass_formula}}{liguid drop model}. Let us remind ourselves about what we did by looking at the code. - -We restate the parts of the code we are most interested in. -\bpycod -# Common imports -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from IPython.display import display -import os - -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("MassEval2016.dat"),'r') - - -# Read the experimental data with Pandas -Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), - names=('N', 'Z', 'A', 'Element', 'Ebinding'), - widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), - header=39, - index_col=False) - -# Extrapolated values are indicated by '#' in place of the decimal place, so -# the Ebinding column won't be numeric. Coerce to float and drop these entries. -Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') -Masses = Masses.dropna() -# Convert from keV to MeV. -Masses['Ebinding'] /= 1000 - -# Group the DataFrame by nucleon number, A. -Masses = Masses.groupby('A') -# Find the rows of the grouped DataFrame with the maximum binding energy. -Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) -A = Masses['A'] -Z = Masses['Z'] -N = Masses['N'] -Element = Masses['Element'] -Energies = Masses['Ebinding'] - -# Now we set up the design matrix X -X = np.zeros((len(A),5)) -X[:,0] = 1 -X[:,1] = A -X[:,2] = A**(2.0/3.0) -X[:,3] = A**(-1.0/3.0) -X[:,4] = A**(-1.0) -# Then nice printout using pandas -DesignMatrix = pd.DataFrame(X) -DesignMatrix.index = A -DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A'] -display(DesignMatrix) -\epycod - -With $\bm{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as -\[ -\bm{\tilde{y}}= \bm{X}\bm{\beta}, -\] -throughout these lectures. - - -% !split -\subsection{Optimizing our parameters, more details} - -% --- begin paragraph admon --- -\paragraph{} -With the above we use the design matrix to define the approximation $\bm{\tilde{y}}$ via the unknown quantity $\bm{\beta}$ as -\[ -\bm{\tilde{y}}= \bm{X}\bm{\beta}, -\] -and in order to find the optimal parameters $\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parameterized values $\tilde{y}_i$, namely -\[ -C(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, -\] -or using the matrix $\bm{X}$ and in a more compact matrix-vector notation as -\[ -C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}^T\bm{\beta}\right)^T\left(\bm{y}-\bm{X}^T\bm{\beta}\right)\right\}. -\] -This function is one possible way to define the so-called cost function. - - - -It is also common to define -the function $Q$ as - -\[ -C(\bm{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, -\] -since when taking the first derivative with respect to the unknown parameters $\beta$, the factor of $2$ cancels out. -% --- end paragraph admon --- - - - - -% !split -\subsection{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} - -The function -\[ -C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}, -\] -can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises) -\[ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -\] - -where $\langle y_i \rangle$ is the mean value. Keep in mind also that -till now we have treated $y_i$ as the exact value. Normally, the -response (dependent or outcome) variable $y_i$ the outcome of a -numerical experiment or another type of experiment and is thus only an -approximation to the true value. It is then always accompanied by an -error estimate, often limited to a statistical error estimate given by -the standard deviation discussed earlier. In the discussion here we -will treat $y_i$ as our exact value for the response variable. - -In order to find the parameters $\beta_i$ we will then minimize the spread of $C(\bm{\beta})$, that is we are going to solve the problem -\[ -{\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\}. -\] -In practical terms it means we will require -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -\] -which results in -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -\] -or in a matrix-vector form as -\[ -\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right). -\] -% --- end paragraph admon --- - - - - -% !split -\subsection{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -We can rewrite -\[ -\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right), -\] -as -\[ -\bm{X}^T\bm{y} = \bm{X}^T\bm{X}\bm{\beta}, -\] -and if the matrix $\bm{X}^T\bm{X}$ is invertible we have the solution -\[ -\bm{\beta} =\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] - -We note also that since our design matrix is defined as $\bm{X}\in -{\mathbb{R}}^{n\times p}$, the product $\bm{X}^T\bm{X} \in -{\mathbb{R}}^{p\times p}$. In the above case we have that $p \ll n$, -in our case $p=5$ meaning that we end up with inverting a small -$5\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional -matrices to invert. The methods discussed here and for many other -supervised learning algorithms like classification with logistic -regression or support vector machines, exhibit dimensionalities which -allow for the usage of direct linear algebra methods such as \textbf{LU} decomposition or \textbf{Singular Value Decomposition} (SVD) for finding the inverse of the matrix -$\bm{X}^T\bm{X}$. -% --- end paragraph admon --- - - - -% !split -\subsection{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -The residuals $\bm{\epsilon}$ are in turn given by -\[ -\bm{\epsilon} = \bm{y}-\bm{\tilde{y}} = \bm{y}-\bm{X}\bm{\beta}, -\] -and with -\[ -\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, -\] -we have -\[ -\bm{X}^T\bm{\epsilon}=\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, -\] -meaning that the solution for $\bm{\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. -% --- end paragraph admon --- - - - - -Let us now return to our nuclear binding energies and simply code the above equations. - -% !split -\subsection{Own code for Ordinary Least Squares} - -It is rather straightforward to implement the matrix inversion and obtain the parameters $\bm{\beta}$. After having defined the matrix $\bm{X}$ we simply need to -write -\bpycod -# matrix inversion to find beta -beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies) -# and then make the prediction -ytilde = X @ beta -\epycod -Alternatively, you can use the least squares functionality in \textbf{Numpy} as -\bpycod -fit = np.linalg.lstsq(X, Energies, rcond =None)[0] -ytildenp = np.dot(fit,X.T) -\epycod - -And finally we plot our fit with and compare with data -\bpycod -Masses['Eapprox'] = ytilde -# Generate a plot comparing the experimental with the fitted values values. -fig, ax = plt.subplots() -ax.set_xlabel(r'$A = N + Z$') -ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') -ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, - label='Ame2016') -ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', - label='Fit') -ax.legend() -save_fig("Masses2016OLS") -plt.show() -\epycod - -% !split -\subsection{Adding error analysis and training set up} - -We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. -Since we are not using _Scikit-Learn here we can define our own $R2$ function as -\bpycod -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) -\epycod -and we would be using it as -\bpycod -print(R2(Energies,ytilde)) -\epycod - -We can easily add our \textbf{MSE} score as -\bpycod -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -print(MSE(Energies,ytilde)) -\epycod -and finally the relative error as -\bpycod -def RelativeError(y_data,y_model): - return abs((y_data-y_model)/y_data) -print(RelativeError(Energies, ytilde)) -\epycod - - - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -Normally, the response (dependent or outcome) variable $y_i$ is the -outcome of a numerical experiment or another type of experiment and is -thus only an approximation to the true value. It is then always -accompanied by an error estimate, often limited to a statistical error -estimate given by the standard deviation discussed earlier. In the -discussion here we will treat $y_i$ as our exact value for the -response variable. - -Introducing the standard deviation $\sigma_i$ for each measurement -$y_i$, we define now the $\chi^2$ function (omitting the $1/n$ term) -as - -\[ -\chi^2(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\frac{1}{\bm{\Sigma^2}}\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, -\] -where the matrix $\bm{\Sigma}$ is a diagonal matrix with $\sigma_i$ as matrix elements. -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -In order to find the parameters $\beta_i$ we will then minimize the spread of $\chi^2(\bm{\beta})$ by requiring -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -\] -which results in -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -\] -or in a matrix-vector form as -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right). -\] -where we have defined the matrix $\bm{A} =\bm{X}/\bm{\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\sigma_i$ and the vector $\bm{b}$ with elements $b_i = y_i/\sigma_i$. -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -We can rewrite -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right), -\] -as -\[ -\bm{A}^T\bm{b} = \bm{A}^T\bm{A}\bm{\beta}, -\] -and if the matrix $\bm{A}^T\bm{A}$ is invertible we have the solution -\[ -\bm{\beta} =\left(\bm{A}^T\bm{A}\right)^{-1}\bm{A}^T\bm{b}. -\] -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -If we then introduce the matrix -\[ -\bm{H} = \left(\bm{A}^T\bm{A}\right)^{-1}, -\] -we have then the following expression for the parameters $\beta_j$ (the matrix elements of $\bm{H}$ are $h_{ij}$) -\[ -\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} -\] -We state without proof the expression for the uncertainty in the parameters $\beta_j$ as (we leave this as an exercise) -\[ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -\] -resulting in -\[ -\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! -\] -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} -The first step here is to approximate the function $y$ with a first-order polynomial, that is we write -\[ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -\] -By computing the derivatives of $\chi^2$ with respect to $\beta_0$ and $\beta_1$ show that these are given by -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -\] -and -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -\] -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -For a linear fit (a first-order polynomial) we don't need to invert a matrix!! -Defining -\[ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -\] - -\[ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -\] - -\[ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -\] - -\[ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -\] - -\[ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -\] - -we obtain - -\[ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -\] - -\[ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -\] - -This approach (different linear and non-linear regression) suffers -often from both being underdetermined and overdetermined in the -unknown coefficients $\beta_i$. A better approach is to use the -Singular Value Decomposition (SVD) method discussed below. Or using -Lasso and Ridge regression. See below. -% --- end paragraph admon --- - - - - -% !split -\subsection{Fitting an Equation of State for Dense Nuclear Matter} - -Before we continue, let us introduce yet another example. We are going to fit the -nuclear equation of state using results from many-body calculations. -The equation of state we have made available here, as function of -density, has been derived using modern nucleon-nucleon potentials with -\href{{https://www.sciencedirect.com/science/article/pii/S0370157399001106}}{the addition of three-body -forces}. This -time the file is presented as a standard \textbf{csv} file. - -The beginning of the Python code here is similar to what you have seen before, -with the same initializations and declarations. We use also \textbf{pandas} -again, rather extensively in order to organize our data. - -The difference now is that we use \textbf{Scikit-Learn's} regression tools -instead of our own matrix inversion implementation. Furthermore, we -sneak in \textbf{Ridge} regression (to be discussed below) which includes a -hyperparameter $\lambda$, also to be explained below. - -% !split -\subsection{The code} - -\bpycod -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import matplotlib.pyplot as plt -import sklearn.linear_model as skl -from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error - -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organize the data into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops -X = np.zeros((len(Density),4)) -X[:,3] = Density**(4.0/3.0) -X[:,2] = Density -X[:,1] = Density**(2.0/3.0) -X[:,0] = 1 - -# We use now Scikit-Learn's linear regressor and ridge regressor -# OLS part -clf = skl.LinearRegression().fit(X, Energies) -ytilde = clf.predict(X) -EoS['Eols'] = ytilde -# The mean squared error -print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(Energies, ytilde)) -# Mean absolute error -print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde)) -print(clf.coef_, clf.intercept_) - -# The Ridge regression with a hyperparameter lambda = 0.1 -_lambda = 0.1 -clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies) -yridge = clf_ridge.predict(X) -EoS['Eridge'] = yridge -# The mean squared error -print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(Energies, yridge)) -# Mean absolute error -print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge)) -print(clf_ridge.coef_, clf_ridge.intercept_) - -fig, ax = plt.subplots() -ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$') -ax.set_ylabel(r'Energy per particle') -ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2, - label='Theoretical data') -ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m', - label='OLS') -ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g', - label='Ridge $\lambda = 0.1$') -ax.legend() -save_fig("EoSfitting") -plt.show() -\epycod - -The above simple polynomial in density $\rho$ gives an excellent fit -to the data. Can you give an interpretation of the various powers of $\rho$? - -We note also that there is a small deviation between the -standard OLS and the Ridge regression at higher densities. We discuss this in more detail -below. - - -% !split -\subsection{Splitting our Data in Training and Test data} - -It is normal in essentially all Machine Learning studies to split the -data in a training set and a test set (sometimes also an additional -validation set). \textbf{Scikit-Learn} has an own function for this. There -is no explicit recipe for how much data should be included as training -data and say test data. An accepted rule of thumb is to use -approximately $2/3$ to $4/5$ of the data as training data. We will -postpone a discussion of this splitting to the end of these notes and -our discussion of the so-called \textbf{bias-variance} tradeoff. Here we -limit ourselves to repeat the above equation of state fitting example -but now splitting the data into a training set and a test set. - -\bpycod -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organized into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops -X = np.zeros((len(Density),5)) -X[:,0] = 1 -X[:,1] = Density**(2.0/3.0) -X[:,2] = Density -X[:,3] = Density**(4.0/3.0) -X[:,4] = Density**(5.0/3.0) -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) -# matrix inversion to find beta -beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train) -# and then make the prediction -ytilde = X_train @ beta -print("Training R2") -print(R2(y_train,ytilde)) -print("Training MSE") -print(MSE(y_train,ytilde)) -ypredict = X_test @ beta -print("Test R2") -print(R2(y_test,ypredict)) -print("Test MSE") -print(MSE(y_test,ypredict)) -\epycod - - -% !split -\subsection{The singular value decomposition} - - -% --- begin paragraph admon --- -\paragraph{} - -The examples we have looked at so far are cases where we normally can -invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion as we -did both for the masses and the fitting of the equation of state, -leads to row vectors of the design matrix which are essentially -orthogonal due to the polynomial character of our model. This may -however not the be case in general and a standard matrix inversion -algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit -the coupling constant of the widely used Ising model. -There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. - -This is given by the \textbf{Singular Value Decomposition} algorithm, perhaps -the most powerful linear algebra algorithm. Let us look at a -different example where we may have problems with the standard matrix -inversion algorithm. Thereafter we dive into the math of the SVD. -% --- end paragraph admon --- - - - -% !split -\subsection{The Ising model} - -The one-dimensional Ising model with nearest neighbor interaction, no -external field and a constant coupling constant $J$ is given by - -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\end{align} - -where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins -in the system is determined by $L$. For the one-dimensional system -there is no phase transition. - -We will look at a system of $L = 40$ spins with a coupling constant of -$J = 1$. To get enough training data we will generate 10000 states -with their respective energies. - - -\bpycod -import numpy as np -import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import make_axes_locatable -import seaborn as sns -import scipy.linalg as scl -from sklearn.model_selection import train_test_split -import tqdm -sns.set(color_codes=True) -cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') - -L = 40 -n = int(1e4) - -spins = np.random.choice([-1, 1], size=(n, L)) -J = 1.0 - -energies = np.zeros(n) - -for i in range(n): - energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) -\epycod - -Here we use ordinary least squares -regression to predict the energy for the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use linear regression to fit a value for -the coupling constant to achieve this. - -% !split -\subsection{Reformulating the problem to suit regression} - -A more general form for the one-dimensional Ising model is - -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\end{align} - -Here we allow for interactions beyond the nearest neighbors and a state dependent -coupling constant. This latter expression can be formulated as -a matrix-product -\begin{align} - \bm{H} = \bm{X} J, -\end{align} - -where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the -elements $-J_{jk}$. This form of writing the energy fits perfectly -with the form utilized in linear regression, that is - -\begin{align} - \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}, -\end{align} - -We split the data in training and test data as discussed in the previous example - -\bpycod -X = np.zeros((n, L ** 2)) -for i in range(n): - X[i] = np.outer(spins[i], spins[i]).ravel() -y = energies -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) -\epycod - -% !split -\subsection{Linear regression} - -In the ordinary least squares method we choose the cost function - -\begin{align} - C(\bm{X}, \bm{\beta})= \frac{1}{n}\left\{(\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y})\right\}. -\end{align} - -We then find the extremal point of $C$ by taking the derivative with respect to $\bm{\beta}$ as discussed above. -This yields the expression for $\bm{\beta}$ to be - -\[ - \bm{\beta} = \frac{\bm{X}^T \bm{y}}{\bm{X}^T \bm{X}}, -\] - -which immediately imposes some requirements on $\bm{X}$ as there must exist -an inverse of $\bm{X}^T \bm{X}$. If the expression we are modeling contains an -intercept, i.e., a constant term, we must make sure that the -first column of $\bm{X}$ consists of $1$. We do this here - -\bpycod -X_train_own = np.concatenate( - (np.ones(len(X_train))[:, np.newaxis], X_train), - axis=1 -) -X_test_own = np.concatenate( - (np.ones(len(X_test))[:, np.newaxis], X_test), - axis=1 -) -\epycod - -\bpycod -def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray: - return scl.inv(x.T @ x) @ (x.T @ y) -beta = ols_inv(X_train_own, y_train) -\epycod - - -% !split -\subsection{Singular Value decomposition} - -Doing the inversion directly turns out to be a bad idea since the matrix -$\bm{X}^T\bm{X}$ is singular. An alternative approach is to use the \textbf{singular -value decomposition}. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for $\bm{\beta}$ as - -\[ - \bm{\beta} = \bm{X}^{+}\bm{y}, -\] - -where the pseudoinverse of $\bm{X}$ is given by - -\[ - \bm{X}^{+} = \frac{\bm{X}^T}{\bm{X}^T\bm{X}}. -\] - -Using singular value decomposition we can decompose the matrix $\bm{X} = \bm{U}\bm{\Sigma} \bm{V}^T$, -where $\bm{U}$ and $\bm{V}$ are orthogonal(unitary) matrices and $\bm{\Sigma}$ contains the singular values (more details below). -where $X^{+} = V\Sigma^{+} U^T$. This reduces the equation for -$\omega$ to -\begin{align} - \bm{\beta} = \bm{V}\bm{\Sigma}^{+} \bm{U}^T \bm{y}. -\end{align} - -Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as $\mathcal{O}(n^3)$, where $n$ is the number of elements in a -general matrix. Instead, doing $QR$-factorization and solving the -linear system as an equation would reduce this down to -$\mathcal{O}(n^2)$ operations. - - -\bpycod -def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray: - u, s, v = scl.svd(x) - return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y -\epycod - -\bpycod -beta = ols_svd(X_train_own,y_train) -\epycod - -When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here - -\bpycod -J = beta[1:].reshape(L, L) -\epycod - -A way of looking at the coefficients in $J$ is to plot the matrices as images. - - -\bpycod -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J, **cmap_args) -plt.title("OLS", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) -plt.show() -\epycod -It is interesting to note that OLS -considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as -valid matrix elements for $J$. -In our discussion below on hyperparameters and Ridge and Lasso regression we will see that -this problem can be removed, partly and only with Lasso regression. - -In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? - - -% !split -\subsection{Linear Regression Problems} - -One of the typical problems we encounter with linear regression, in particular -when the matrix $\bm{X}$ (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of $\bm{X}$ -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} - -The columns of $\bm{X}$ are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of $\mathbf{X}$ is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. - -Super-collinearity of an $(n \times p)$-dimensional design matrix $\mathbf{X}$ implies -that the inverse of the matrix $\bm{X}^T\bm{x}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -\begin{align*} -\bm{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -We see easily that $\mbox{det}(\bm{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined. -This is equivalent to saying that the matrix $\bm{X}$ has at least an eigenvalue which is zero. - - -% !split -\subsection{Fixing the singularity} - -If our design matrix $\bm{X}$ which enters the linear regression problem -\begin{align} -\bm{\beta} & = (\bm{X}^{T} \bm{X})^{-1} \bm{X}^{T} \bm{y}, -\end{align} -has linearly dependent column vectors, we will not be able to compute the inverse -of $\bm{X}^T\bm{X}$ and we cannot find the parameters (estimators) $\beta_i$. -The estimators are only well-defined if $(\bm{X}^{T}\bm{X})^{-1}$ exits. -This is more likely to happen when the matrix $\bm{X}$ is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters $\beta_i$ cannot be estimated. - -A cheap \emph{ad hoc} approach is simply to add a small diagonal component to the matrix to invert, that is we change -\[ -\bm{X}^{T} \bm{X} \rightarrow \bm{X}^{T} \bm{X}+\lambda \bm{I}, -\] -where $\bm{I}$ is the identity matrix. When we discuss \textbf{Ridge} regression this is actually what we end up evaluating. The parameter $\lambda$ is called a hyperparameter. More about this later. - - - -% !split -\subsection{Basic math of the SVD} - - -From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is -a so-called \href{{https://en.wikipedia.org/wiki/Normal_matrix}}{normal matrix}, that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$ -we have $\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ or if $\bm{X}\in {\mathbb{C}}^{n\times n}$ we have $\bm{X}\bm{X}^{\dagger}=\bm{X}^{\dagger}\bm{X}$. -The matrix has then a set of eigenpairs - -\[ -(\lambda_1,\bm{u}_1),\dots, (\lambda_n,\bm{u}_n), -and the eigenvalues are given by the diagonal matrix -\[ -\bm{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). -\] -The matrix $\bm{X}$ can be written in terms of an orthogonal/unitary transformation $\bm{U}$ -\[ -\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T, -\] -with $\bm{U}\bm{U}^T=\bm{I}$ or $\bm{U}\bm{U}^{\dagger}=\bm{I}$. - -Not all square matrices are diagonalizable. A matrix like the one discussed above -\[ -\bm{X} = \begin{bmatrix} -1& -1 \\ -1& -1\\ -\end{bmatrix} -\] -is not diagonalizable, it is a so-called \href{{https://en.wikipedia.org/wiki/Defective_matrix}}{defective matrix}. It is easy to see that the condition -$\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ is not fulfilled. - - -% !split -\subsection{The SVD, a Fantastic Algorithm} - - -However, and this is the strength of the SVD algorithm, any general -matrix $\bm{X}$ can be decomposed in terms of a diagonal matrix and -two orthogonal/unitary matrices. The \href{{https://en.wikipedia.org/wiki/Singular_value_decomposition}}{Singular Value Decompostion -(SVD) theorem} -states that a general $m\times n$ matrix $\bm{X}$ can be written in -terms of a diagonal matrix $\bm{\Sigma}$ of dimensionality $n\times n$ -and two orthognal matrices $\bm{U}$ and $\bm{V}$, where the first has -dimensionality $m \times m$ and the last dimensionality $n\times n$. -We have then - -\[ -\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T -\] - -As an example, the above defective matrix can be decomposed as - -\[ -\bm{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T, -\] - -with eigenvalues $\sigma_1=2$ and $\sigma_2=0$. -The SVD exits always! - - -% !split -\subsection{Another Example} - -Consider the following matrix which can be SVD decomposed as - -\[ -\bm{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T. -\] - -This is a $3\times 2$ matrix which is decomposed in terms of a -$3\times 3$ matrix $\bm{U}$, and a $2\times 2$ matrix $\bm{V}$. It is easy to see -that $\bm{U}$ and $\bm{V}$ are orthogonal (how?). - -And the SVD -decomposition (singular values) gives eigenvalues -$\sigma_i\geq\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=2$, the -eigenvalues (singular values) are zero. - -In the general case, where our design matrix $\bm{X}$ has dimension -$n\times p$, the matrix is thus decomposed into an $n\times n$ -orthogonal matrix $\bm{U}$, a $p\times p$ orthogonal matrix $\bm{V}$ -and a diagonal matrix $\bm{\Sigma}$ with $r=\mathrm{min}(n,p)$ -singular values $\sigma_i\lg 0$ on the main diagonal and zeros filling -the rest of the matrix. There are at most $p$ singular values -assuming that $n > p$. In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have $p > n$. These are often cases that lead to -near singular or singular matrices. - -The columns of $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors. - -% !split -\subsection{Economy-size SVD} - -If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n -\times n$. The last $n-p$ columns of $\bm{U}$ become however -irrelevant in our calculations since they are multiplied with the -zeros in $\bm{\Sigma}$. - -The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, $\bm{\Sigma}$, along with the columns -in either $\bm{U}$ or $\bm{V}$ that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. - -If $n > p$, we keep only the first $p$ columns of $\bm{U}$ and $\bm{\Sigma}$ has dimension $p\times p$. -If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\Sigma}$ has dimension $n\times n$. -The $n=p$ case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. - -% !split -\subsection{Mathematical Properties} - -There are several interesting mathematical properties which will be -relevant when we are going to discuss the differences between say -ordinary least squares (OLS) and \textbf{Ridge} regression. - -We have from OLS that the parameters of the linear approximation are given by -\[ -\bm{\tilde{y}} = \bm{X}\bm{\beta} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] - -The matrix to invert can be rewritten in terms of our SVD decomposition as - -\[ -\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T. -\] -Using the orthogonality properties of $\bm{U}$ we have - -\[ -\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T = \bm{V}\bm{D}\bm{V}^T, -\] -with $\bm{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. - -This means that -\[ -(\bm{X}^T\bm{X})\bm{V} = \bm{V}\bm{D}, -\] -that is the eigenvectors of $(\bm{X}^T\bm{X})$ are given by the columns of the right singular matrix of $\bm{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that -\[ -(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}, -\] -that is, the eigenvectors of $(\bm{X}\bm{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. - -Going back to our OLS equation we have -\[ -\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}. -\] -We will come back to this expression when we discuss Ridge regression. - - -% !split -\subsection{Ridge and LASSO Regression} - -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_{\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\}. -\] -or we can state it as -\[ -{\displaystyle \min_{\bm{\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 \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, -\] -where we have used the definition of a norm-2 vector, that is -\[ -\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. -\] - -By minimizing the above equation with respect to the parameters -$\bm{\beta}$ we could then obtain an analytical expression for the -parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by -defining a new cost function to be optimized, that is - -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 -\] - -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. By defining - -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, -\] - -we have a new optimization equation -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\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 \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. -\] - - -% !split -\subsection{More on Ridge Regression} - -Using the matrix-vector expression for Ridge regression, - -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, -\] - -by taking the derivatives with respect to $\bm{\beta}$ we obtain then -a slightly modified matrix inversion problem which for finite values -of $\lambda$ does not suffer from singularity problems. We obtain - -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, -\] - -with $\bm{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. - -We see that Ridge regression is nothing but the standard -OLS with a modified diagonal term added to $\bm{X}^T\bm{X}$. The -consequences, in particular for our discussion of the bias-variance -are rather interesting. - -Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had -\[ -(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}. -\] - -We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as -\[ -\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y} -\] - - -For Ridge regression this becomes - -\[ -\bm{X}\bm{\beta}^{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, -\] - -with the vectors $\bm{u}_j$ being the columns of $\bm{U}$. - -% !split -\subsection{Interpreting the Ridge results} - -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 $\bm{y}$ with respect to the -orthonormal basis $\bm{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}$. - -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. -Actually, calculating the variance of $\bm{X}\bm{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$. -With a parameter $\lambda$ we can thus shrink the role of specific parameters. - - -% !split -\subsection{More interpretations} - -For the sake of simplicity, let us assume that the design matrix is orthonormal, that is - -\[ -\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. -\] - -In this case the standard OLS results in -\[ -\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, -\] - -and - -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\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. - -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, \href{{https://arxiv.org/abs/1509.09169}}{Wessel van Wieringen's} article is highly recommended. -Similarly, \href{{https://arxiv.org/abs/1803.08823}}{Mehta et al's article} is also recommended. - -% !split -\subsection{Where are we going?} - -Before we proceed, we need to rethink what we have been doing. In our -eager to fit the data, we have omitted several important elements in -our regression analysis. In what follows we will -\begin{enumerate} -\item look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff - -\item introduce resampling techniques like cross-validation, bootstrapping and jackknife and more -\end{enumerate} - -\noindent -This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. - - - - - -% !split -\subsection{Resampling methods} - -% --- begin paragraph admon --- -\paragraph{} -Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. -% --- end paragraph admon --- - - - -% !split -\subsection{Resampling approaches can be computationally expensive} - -% --- begin paragraph admon --- -\paragraph{} - -Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. -% --- end paragraph admon --- - - - -% !split -\subsection{Why resampling methods ?} - -% --- begin paragraph admon --- -\paragraph{Statistical analysis.} - -\begin{itemize} -\item Our simulations can be treated as \emph{computer experiments}. This is particularly the case for Monte Carlo methods - -\item The results can be analysed with the same statistical tools as we would use analysing experimental data. - -\item As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. -\end{itemize} - -\noindent -% --- end paragraph admon --- - - - -% !split -\subsection{Statistical analysis} - -% --- begin paragraph admon --- -\paragraph{} - -\begin{itemize} -\item As in other experiments, many numerical experiments have two classes of errors: -\begin{itemize} - - \item Statistical errors - - \item Systematical errors - -\end{itemize} - -\noindent -\item Statistical errors can be estimated using standard tools from statistics - -\item Systematical errors are method specific and must be treated differently from case to case. -\end{itemize} - -\noindent -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -The \emph{probability distribution function (PDF)} is a function -$p(x)$ on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of $X$ occur: -\[ -p(x) = \mathrm{prob}(X=x) -\] -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us -the \emph{density} of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval $[a,\,b]$ is then just the integral: -\[ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx -\] -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. -% --- end paragraph admon --- - - - - -% !split -\subsection{Statistics, moments} - -% --- begin paragraph admon --- -\paragraph{} -A particularly useful class of special expectation values are the -\emph{moments}. The $n$-th moment of the PDF $p$ is defined as -follows: -\[ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx -\] -The zero-th moment $\langle 1\rangle$ is just the normalization condition of -$p$. The first moment, $\langle x\rangle$, is called the \emph{mean} of $p$ -and often denoted by the letter $\mu$: -\[ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, central moments} - -% --- begin paragraph admon --- -\paragraph{} -A special version of the moments is the set of \emph{central moments}, -the n-th central moment defined as: -\[ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -\] -The zero-th and first central moments are both trivial, equal $1$ and -$0$, respectively. But the second central moment, known as the -\emph{variance} of $p$, is of particular interest. For the stochastic -variable $X$, the variance is denoted as $\sigma^2_X$ or $\mathrm{var}(X)$: -\begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\end{align} -The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle}$ is called the \emph{standard deviation} of $p$. It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the \emph{spread} of $p$ around its mean. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, covariance} - -% --- begin paragraph admon --- -\paragraph{} -Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set $\{X_i\}$ of $n$ -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF $P(x_1,\dots,x_n)$. The \emph{covariance} of two -of the stochastic variables, $X_i$ and $X_j$, is defined as follows: -\begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\label{eq:def_covariance} -\end{align} -with -\[ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, more covariance} - -% --- begin paragraph admon --- -\paragraph{} -If we consider the above covariance as a matrix $C_{ij}=\mathrm{cov}(X_i,\,X_j)$, then the diagonal elements are just the familiar -variances, $C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i)$. It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables $X_i$ and -$X_j$, ($i\neq j$): -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle \\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\end{align} -% --- end paragraph admon --- - - - - - -% !split -\subsection{Statistics, independent variables} - -% --- begin paragraph admon --- -\paragraph{} -If $X_i$ and $X_j$ are independent, we get -$\langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle$, resulting in $\mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j)$. - -Also useful for us is the covariance of linear combinations of -stochastic variables. Let $\{X_i\}$ and $\{Y_i\}$ be two sets of -stochastic variables. Let also $\{a_i\}$ and $\{b_i\}$ be two sets of -scalars. Consider the linear combination: -\[ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j -\] -By the linearity of the expectation value -\[ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, more variance} - -% --- begin paragraph admon --- -\paragraph{} -Now, since the variance is just $\mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i)$, we get -the variance of the linear combination $U = \sum_i a_i X_i$: -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\label{eq:variance_linear_combination} -\end{equation} -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -\[ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -\] -\[ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -\] -which will become very useful in our study of the error in the mean -value of a set of measurements. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics and stochastic processes} - -% --- begin paragraph admon --- -\paragraph{} -A \emph{stochastic process} is a process that produces sequentially a -chain of values: -\[ -\{x_1, x_2,\dots\,x_k,\dots\}. -\] -We will call these -values our \emph{measurements} and the entire set as our measured -\emph{sample}. The action of measuring all the elements of a sample -we will call a stochastic \emph{experiment} since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF $p_X^{\phantom X}(x)$, where $X$ is just the formal symbol for the -stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of -trying to determine the full distribution $p$ we are often only -interested in finding the few lowest moments, like the mean -$\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$. -% --- end paragraph admon --- - - - - -% !split -\subsection{Statistics and sample variables} - -% --- begin paragraph admon --- -\paragraph{} -In practical situations a sample is always of finite size. Let that -size be $n$. The expectation value of a sample, the \emph{sample mean}, is then defined as follows: -\[ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -\] -The \emph{sample variance} is: -\[ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -\] -its square root being the \emph{standard deviation of the sample}. The -\emph{sample covariance} is: -\[ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, sample variance and covariance} - -% --- begin paragraph admon --- -\paragraph{} -Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq.~(\ref{eq:def_covariance}) is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. - -These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean $\mu_X$, variance $\mathrm{var}(X)$ -and covariance $\mathrm{cov}(X,Y)$. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, law of large numbers} - -% --- begin paragraph admon --- -\paragraph{} -The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean $\mu_X^{\phantom X}$ of the chosen PDF: -\[ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} -\] -The sample mean $\bar{x}_n$ works therefore as an estimate of the true -mean $\mu_X^{\phantom X}$. - -What we need to find out is how good an approximation $\bar{x}_n$ is to -$\mu_X^{\phantom X}$. In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the \emph{error} of the sample mean, or -just sample error, and denote it by $\mathrm{err}_X^{\phantom X}$. In -practice, we will only be able to produce an \emph{estimate} of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. -% --- end paragraph admon --- - - - - -% !split -\subsection{Statistics, more on sample error} - -% --- begin paragraph admon --- -\paragraph{} -Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements $x_i$ -can be associated with its own stochastic variable $X_i$. The -stochastic variable $\overline X_n$ for the sample mean $\bar{x}_n$ is -then just a linear combination, already familiar to us: -\[ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i -\] -All the coefficients are just equal $1/n$. The PDF of $\overline X_n$, -denoted by $p_{\overline X_n}(x)$ is the desired PDF of the sample -means. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -The probability density of obtaining a sample mean $\bar x_n$ -is the product of probabilities of obtaining arbitrary values $x_1, -x_2,\dots,x_n$ with the constraint that the mean of the set $\{x_i\}$ -is $\bar x_n$: -\[ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 -\] -And in particular we are interested in its variance $\mathrm{var}(\overline X_n)$. -% --- end paragraph admon --- - - - - - -% !split -\subsection{Statistics, central limit theorem} - -% --- begin paragraph admon --- -\paragraph{} -It is generally not possible to express $p_{\overline X_n}(x)$ in a -closed form given an arbitrary PDF $p_X^{\phantom X}$ and a number -$n$. But for the limit $n\to\infty$ it is possible to make an -approximation. The very important result is called \emph{the central limit theorem}. It tells us that as $n$ goes to infinity, -$p_{\overline X_n}(x)$ approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, $\mu_{X}^{\phantom X}$ -and $\sigma_{X}^{2}$, respectively: -\begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\label{eq:central_limit_gaussian} -\end{equation} -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, more technicalities} - -% --- begin paragraph admon --- -\paragraph{} -The desired variance -$\mathrm{var}(\overline X_n)$, i.e.~the sample error squared -$\mathrm{err}_X^2$, is given by: -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\label{eq:error_exact} -\end{equation} -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -$\mu_{X_i}^{\phantom X}$ of the stochastic variables $X_i$. To -calculate these requires that we know the true multivariate PDF of all -the $X_i$. But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the $X_i$, estimating all properties of -$X_i$ through the measurements of the sample. -% --- end paragraph admon --- - - - - -% !split -\subsection{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -Our estimate of $\mu_{X_i}^{\phantom X}$ is then the sample mean $\bar x$ -itself, in accordance with the the central limit theorem: -\[ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x -\] -Using $\bar x$ in place of $\mu_{X_i}^{\phantom X}$ we can give an -\emph{estimate} of the covariance in Eq.~(\ref{eq:error_exact}) -\[ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, -\] -resulting in -\[ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics and sample variance} - -% --- begin paragraph admon --- -\paragraph{} -By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables $X_i$ -\[ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, -\] -which is approximated as -\begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\label{eq:var_estimate_i_think} -\end{equation} - -Now we can calculate an estimate of the error -$\mathrm{err}_X^{\phantom X}$ of the sample mean $\bar x_n$: -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\label{eq:error_estimate} -\end{align} -which is nothing but the sample covariance divided by the number of -measurements in the sample. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, uncorrelated results} - -% --- begin paragraph admon --- -\paragraph{} - -In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables $X_i$ are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: -\[ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), -\] -resulting in -\begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\label{eq:error_estimate_uncorrel} -\end{equation} -where in the second step we have used Eq.~(\ref{eq:var_estimate_i_think}). -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, computations} - -% --- begin paragraph admon --- -\paragraph{} -For computational purposes one usually splits up the estimate of -$\mathrm{err}_X^2$, given by Eq.~(\ref{eq:error_estimate}), into two -parts -\[ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), -\] -which equals -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k 0$. We say then that the ridge estimator is biased. - -We can also compute the variance as - -\[ -\mbox{Var}[\bm{\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 $\bm{\beta}$ goes to zero. - -With this, we can compute the difference - -\[ -\mbox{Var}[\bm{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\bm{\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 $\bm{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. - -% !split -\subsection{Cross-validation} - -Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e.~the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. - -The setting of \textbf{original} and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the -\emph{training set}, plays the role of \textbf{original} data on which the model is -built. The second of these data sets, called the \emph{test set}, plays the -role of the \textbf{novel} data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of $\lambda$ using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. - - -% !split -\subsection{Computationally expensive} - -The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: - -\begin{itemize} -\item The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set. - -\item In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set. -\end{itemize} - -\noindent -% !split -\subsection{Various steps in cross-validation} - -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this $k$-fold cross-validation structures the data splitting. The -samples are divided into $k$ more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the $k$ subsets -involves a degree of randomness. This may be fully excluded when -choosing $k=n$. This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -% !split -\subsection{How to set up the cross-validation for Ridge and/or Lasso} - -\begin{itemize} -\item Define a range of interest for the penalty parameter. - -\item Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. - -\item Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, as -\end{itemize} - -\noindent -\begin{align*} -\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T} -\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1} -\bm{X}_{-i, \ast}^{T} \bm{y}_{-i} -\end{align*} - -\begin{itemize} -\item Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. - -\item Repeat the first three steps such that each sample plays the role of the test set once. - -\item Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the \emph{cross-validated log-likelihood}. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as -\end{itemize} - -\noindent -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} - -\begin{itemize} -\item The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions. -\end{itemize} - -\noindent -% !split -\subsection{Resampling methods: Jackknife and Bootstrap} - -Two famous -resampling methods are the \textbf{independent bootstrap} and \textbf{the jackknife}. - -The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as \textbf{the dependent bootstrap}. - -The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of $\overline{X}$ (which often is the case), then there is no -need for bootstrapping. - -% !split -\subsection{Resampling methods: Jackknife} - -The Jackknife works by making many replicas of the estimator $\widehat{\theta}$. -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\bm{x} = (x_1,x_2,\cdots,X_n)$. -Let $\bm{x}_i$ denote the vector -\[ -\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -\] - -which equals the vector $\bm{x}$ with the exception that observation -number $i$ is left out. Using this notation, define -$\widehat{\theta}_i$ to be the estimator -$\widehat{\theta}$ computed using $\vec{X}_i$. - - -% !split -\subsection{Jackknife code example} -\bpycod -from numpy import * -from numpy.random import randint, randn -from time import time - -def jackknife(data, stat): - n = len(data);t = zeros(n); inds = arange(n); t0 = time() - ## 'jackknifing' by leaving out an observation for each i - for i in range(n): - t[i] = stat(delete(data,i) ) - - # analysis - print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :") - print("original bias std. error") - print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5)) - - return t - - -# Returns mean of data samples -def stat(data): - return mean(data) - - -mu, sigma = 100, 15 -datapoints = 10000 -x = mu + sigma*random.randn(datapoints) -# jackknife returns the data sample -t = jackknife(x, stat) - -\epycod - - -% !split -\subsection{Resampling methods: Bootstrap} - -% --- begin paragraph admon --- -\paragraph{} -Bootstrapping is a nonparametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: -\begin{enumerate} -\item The bootstrap is quite general, although there are some cases in which it fails. - -\item Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. - -\item It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. - -\item It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples). -\end{enumerate} - -\noindent -% --- end paragraph admon --- - - - - -% !split -\subsection{Resampling methods: Bootstrap background} - -Since $\widehat{\theta} = \widehat{\theta}(\bm{X})$ is a function of random variables, -$\widehat{\theta}$ itself must be a random variable. Thus it has -a pdf, call this function $p(\bm{t})$. The aim of the bootstrap is to -estimate $p(\bm{t})$ by the relative frequency of -$\widehat{\theta}$. You can think of this as using a histogram -in the place of $p(\bm{t})$. If the relative frequency closely -resembles $p(\vec{t})$, then using numerics, it is straight forward to -estimate all the interesting parameters of $p(\bm{t})$ using point -estimators. - - -% !split -\subsection{Resampling methods: More Bootstrap background} - -In the case that $\widehat{\theta}$ has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of $X_i$, $p(x)$, had been known, then it would have -been straight forward to do this by: -\begin{enumerate} -\item Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \cdots, X_n^*)$. - -\item Then using these numbers, we could compute a replica of $\widehat{\theta}$ called $\widehat{\theta}^*$. -\end{enumerate} - -\noindent -By repeated use of (1) and (2), many -estimates of $\widehat{\theta}$ could have been obtained. The -idea is to use the relative frequency of $\widehat{\theta}^*$ -(think of a histogram) as an estimate of $p(\bm{t})$. - -% !split -\subsection{Resampling methods: Bootstrap approach} - -But -unless there is enough information available about the process that -generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general -unknown. Therefore, \href{{https://projecteuclid.org/euclid.aos/1176344552}}{Efron in 1979} asked the -question: What if we replace $p(x)$ by the relative frequency -of the observation $X_i$; if we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - - -Instead of generating the histogram for the relative -frequency of the observation $X_i$, just draw the values -$(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector -$\bm{X}$. - -% !split -\subsection{Resampling methods: Bootstrap steps} - -The independent bootstrap works like this: - -\begin{enumerate} -\item Draw with replacement $n$ numbers for the observed variables $\bm{x} = (x_1,x_2,\cdots,x_n)$. - -\item Define a vector $\bm{x}^*$ containing the values which were drawn from $\bm{x}$. - -\item Using the vector $\bm{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\bm{x}^*$. - -\item Repeat this process $k$ times. -\end{enumerate} - -\noindent -When you are done, you can draw a histogram of the relative frequency -of $\widehat \theta^*$. This is your estimate of the probability -distribution $p(t)$. Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of $\widehat{\theta}^*$. Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of $\widehat -\theta$, apply the etsimator $\widehat \sigma^2$ to the values -$\widehat \theta ^*$. - - -% !split -\subsection{Code example for the Bootstrap method} - -The following code starts with a Gaussian distribution with mean value -$\mu =100$ and variance $\sigma=15$. We use this to generate the data -used in the bootstrap analysis. The bootstrap analysis returns a data -set after a given number of bootstrap operations (as many as we have -data points). This data set consists of estimated mean values for each -bootstrap operation. The histogram generated by the bootstrap method -shows that the distribution for these mean values is also a Gaussian, -centered around the mean value $\mu=100$ but with standard deviation -$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in -this case the same as the number of original data points). The value -of the standard deviation is what we expect from the central limit -theorem. - - -\bpycod -from numpy import * -from numpy.random import randint, randn -from time import time -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt - -# Returns mean of bootstrap samples -def stat(data): - return mean(data) - -# Bootstrap algorithm -def bootstrap(data, statistic, R): - t = zeros(R); n = len(data); inds = arange(n); t0 = time() - # non-parametric bootstrap - for i in range(R): - t[i] = statistic(data[randint(0,n,n)]) - - # analysis - print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") - print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) - return t - - -mu, sigma = 100, 15 -datapoints = 10000 -x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample -t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data -n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) - -# add a 'best fit' line -y = mlab.normpdf( binsboot, mean(t), std(t)) -lt = plt.plot(binsboot, y, 'r--', linewidth=1) -plt.xlabel('Smarts') -plt.ylabel('Probability') -plt.axis([99.5, 100.6, 0, 3.0]) -plt.grid(True) - -plt.show() - -\epycod - - -% !split -\subsection{Code Example for Cross-validation and $k$-fold Cross-validation} - -The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. -\bpycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.model_selection import KFold -from sklearn.linear_model import Ridge -from sklearn.model_selection import cross_val_score -from sklearn.preprocessing import PolynomialFeatures - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(3155) - -# Generate the data. -nsamples = 100 -x = np.random.randn(nsamples) -y = 3*x**2 + np.random.randn(nsamples) - -## Cross-validation on Ridge regression using KFold only - -# Decide degree on polynomial to fit -poly = PolynomialFeatures(degree = 6) - -# Decide which values of lambda to use -nlambdas = 500 -lambdas = np.logspace(-3, 5, nlambdas) - -# Initialize a KFold instance -k = 5 -kfold = KFold(n_splits = k) - -# Perform the cross-validation to estimate MSE -scores_KFold = np.zeros((nlambdas, k)) - -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - j = 0 - for train_inds, test_inds in kfold.split(x): - xtrain = x[train_inds] - ytrain = y[train_inds] - - xtest = x[test_inds] - ytest = y[test_inds] - - Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) - ridge.fit(Xtrain, ytrain[:, np.newaxis]) - - Xtest = poly.fit_transform(xtest[:, np.newaxis]) - ypred = ridge.predict(Xtest) - - scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) - - j += 1 - i += 1 - - -estimated_mse_KFold = np.mean(scores_KFold, axis = 1) - -## Cross-validation using cross_val_score from sklearn along with KFold - -# kfold is an instance initialized above as: -# kfold = KFold(n_splits = k) - -estimated_mse_sklearn = np.zeros(nlambdas) -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - - X = poly.fit_transform(x[:, np.newaxis]) - estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) - - # cross_val_score return an array containing the estimated negative mse for every fold. - # we have to the the mean of every array in order to get an estimate of the mse of the model - estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) - - i += 1 - -## Plot and compare the slightly different ways to perform cross-validation - -plt.figure() - -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') - -plt.xlabel('log10(lambda)') -plt.ylabel('mse') - -plt.legend() - -plt.show() - -\epycod - - -% !split -\subsection{The bias-variance tradeoff} - - -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset $\mathcal{L}$ consisting of the data -$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$. - -Let us assume that the true data is generated from a noisy model - -\[ -\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon} -\] - -where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$. - -In our derivation of the ordinary least squares method we defined then -an approximation to the function $f$ in terms of the parameters -$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model, -that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$. - -Thereafter we found the parameters $\bm{\beta}$ by optimizing the means squared error via the so-called cost function -\[ -C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]. -\] - -We can rewrite this as -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\sigma^2. -\] - -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error $\bm{\epsilon}$. - -To derive this equation, we need to recall that the variance of $\bm{y}$ and $\bm{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\bm{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\bm{\tilde{y}}$. -We use a more compact notation in terms of the expectation value -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}})^2\right], -\] -and adding and subtracting $\mathbb{E}\left[\bm{\tilde{y}}\right]$ we get -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}}+\mathbb{E}\left[\bm{\tilde{y}}\right]-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right], -\] -which, using the abovementioned expectation values can be rewritten as -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\bm{\tilde{y}}\right]+\sigma^2, -\] -that is the rewriting in terms of the so-called bias, the variance of the model $\bm{\tilde{y}}$ and the variance of $\bm{\epsilon}$. - - - - - -% !split -\subsection{Example code for Bias-Variance tradeoff} -\bpycod -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 500 -n_boostraps = 100 -degree = 18 # A quite high value, just to show. -noise = 0.1 - -# Make data set. -x = np.linspace(-1, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) - -# Hold out some test data that is never used in training. -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -# Combine x transformation and model into one operation. -# Not neccesary, but convenient. -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - -# The following (m x n_bootstraps) matrix holds the column vectors y_pred -# for each bootstrap iteration. -y_pred = np.empty((y_test.shape[0], n_boostraps)) -for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - - # Evaluate the new model on the same test data each time. - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - -# Note: Expectations and variances taken w.r.t. different training -# data sets, hence the axis=1. Subsequent means are taken across the test data -# set in order to obtain a total value, but before this we have error/bias/variance -# calculated per data point in the test set. -# Note 2: The use of keepdims=True is important in the calculation of bias as this -# maintains the column vector form. Dropping this yields very unexpected results. -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) -print('Error:', error) -print('Bias^2:', bias) -print('Var:', variance) -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) - -plt.plot(x[::5, :], y[::5, :], label='f(x)') -plt.scatter(x_test, y_test, label='Data points') -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') -plt.legend() -plt.show() - -\epycod - - -% !split -\subsection{Understanding what happens} -\bpycod -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 40 -n_boostraps = 100 -maxdegree = 14 - - -# Make data set. -x = np.linspace(-3, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) -error = np.zeros(maxdegree) -bias = np.zeros(maxdegree) -variance = np.zeros(maxdegree) -polydegree = np.zeros(maxdegree) -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -for degree in range(maxdegree): - model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - y_pred = np.empty((y_test.shape[0], n_boostraps)) - for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) - variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) - print('Polynomial degree:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) - -plt.plot(polydegree, np.log10(error), label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') -plt.legend() -plt.show() - - - - -\epycod - -% !split -\subsection{Summing up} - - - - -The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - - - -The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below $Var(\epsilon)$, the irreducible error. - - -What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - - -% !split -\subsection{Another Example rom Scikit-Learn's Repository} -\bpycod -""" -============================ -Underfitting vs. Overfitting -============================ - -This example demonstrates the problems of underfitting and overfitting and -how we can use linear regression with polynomial features to approximate -nonlinear functions. The plot shows the function that we want to approximate, -which is a part of the cosine function. In addition, the samples from the -real function and the approximations of different models are displayed. The -models have polynomial features of different degrees. We can see that a -linear function (polynomial with degree 1) is not sufficient to fit the -training samples. This is called **underfitting**. A polynomial of degree 4 -approximates the true function almost perfectly. However, for higher degrees -the model will **overfit** the training data, i.e. it learns the noise of the -training data. -We evaluate quantitatively **overfitting** / **underfitting** by using -cross-validation. We calculate the mean squared error (MSE) on the validation -set, the higher, the less likely the model generalizes correctly from the -training data. -""" - -print(__doc__) - -import numpy as np -import matplotlib.pyplot as plt -from sklearn.pipeline import Pipeline -from sklearn.preprocessing import PolynomialFeatures -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import cross_val_score - - -def true_fun(X): - return np.cos(1.5 * np.pi * X) - -np.random.seed(0) - -n_samples = 30 -degrees = [1, 4, 15] - -X = np.sort(np.random.rand(n_samples)) -y = true_fun(X) + np.random.randn(n_samples) * 0.1 - -plt.figure(figsize=(14, 5)) -for i in range(len(degrees)): - ax = plt.subplot(1, len(degrees), i + 1) - plt.setp(ax, xticks=(), yticks=()) - - polynomial_features = PolynomialFeatures(degree=degrees[i], - include_bias=False) - linear_regression = LinearRegression() - pipeline = Pipeline([("polynomial_features", polynomial_features), - ("linear_regression", linear_regression)]) - pipeline.fit(X[:, np.newaxis], y) - - # Evaluate the models using crossvalidation - scores = cross_val_score(pipeline, X[:, np.newaxis], y, - scoring="neg_mean_squared_error", cv=10) - - X_test = np.linspace(0, 1, 100) - plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") - plt.plot(X_test, true_fun(X_test), label="True function") - plt.scatter(X, y, edgecolor='b', s=20, label="Samples") - plt.xlabel("x") - plt.ylabel("y") - plt.xlim((0, 1)) - plt.ylim((-2, 2)) - plt.legend(loc="best") - plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( - degrees[i], -scores.mean(), scores.std())) -plt.show() -\epycod - - - -% !split -\subsection{The one-dimensional Ising model} - -Let us bring back the Ising model again, but now with an additional -focus on Ridge and Lasso regression as well. We repeat some of the -basic parts of the Ising model and the setup of the training and test -data. The one-dimensional Ising model with nearest neighbor -interaction, no external field and a constant coupling constant $J$ is -given by - -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\end{align} -where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins in the system is determined by $L$. For the one-dimensional system there is no phase transition. - -We will look at a system of $L = 40$ spins with a coupling constant of $J = 1$. To get enough training data we will generate 10000 states with their respective energies. - - -\bpycod -import numpy as np -import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import make_axes_locatable -import seaborn as sns -import scipy.linalg as scl -from sklearn.model_selection import train_test_split -import sklearn.linear_model as skl -import tqdm -sns.set(color_codes=True) -cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') - -L = 40 -n = int(1e4) - -spins = np.random.choice([-1, 1], size=(n, L)) -J = 1.0 - -energies = np.zeros(n) - -for i in range(n): - energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) -\epycod - -A more general form for the one-dimensional Ising model is - -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\end{align} - -Here we allow for interactions beyond the nearest neighbors and a more -adaptive coupling matrix. This latter expression can be formulated as -a matrix-product on the form -\begin{align} - H = X J, -\end{align} - -where $X_{jk} = s_j s_k$ and $J$ is the matrix consisting of the -elements $-J_{jk}$. This form of writing the energy fits perfectly -with the form utilized in linear regression, viz. -\begin{align} - \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}. -\end{align} -We organize the data as we did above -\bpycod -X = np.zeros((n, L ** 2)) -for i in range(n): - X[i] = np.outer(spins[i], spins[i]).ravel() -y = energies -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96) - -X_train_own = np.concatenate( - (np.ones(len(X_train))[:, np.newaxis], X_train), - axis=1 -) - -X_test_own = np.concatenate( - (np.ones(len(X_test))[:, np.newaxis], X_test), - axis=1 -) -\epycod - -We will do all fitting with \textbf{Scikit-Learn}, - -\bpycod -clf = skl.LinearRegression().fit(X_train, y_train) -\epycod -When extracting the $J$-matrix we make sure to remove the intercept -\bpycod -J_sk = clf.coef_.reshape(L, L) -\epycod -And then we plot the results -\bpycod -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_sk, **cmap_args) -plt.title("LinearRegression from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) -plt.show() -\epycod -The results perfectly with our previous discussion where we used our own code. - -% !split -\subsection{Ridge regression} - -Having explored the ordinary least squares we move on to ridge -regression. In ridge regression we include a \textbf{regularizer}. This -involves a new cost function which leads to a new estimate for the -weights $\bm{\beta}$. This results in a penalized regression problem. The -cost function is given by - -\begin{align} - C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \bm{\beta}^T\bm{\beta}. -\end{align} -\bpycod -_lambda = 0.1 -clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train) -J_ridge_sk = clf_ridge.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_ridge_sk, **cmap_args) -plt.title("Ridge from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - -plt.show() -\epycod - -% !split -\subsection{LASSO regression} - -In the \textbf{Least Absolute Shrinkage and Selection Operator} (LASSO)-method we get a third cost function. - -\begin{align} - C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \sqrt{\bm{\beta}^T\bm{\beta}}. -\end{align} - -Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from \textbf{Scikit-Learn}. - -\bpycod -clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train) -J_lasso_sk = clf_lasso.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_lasso_sk, **cmap_args) -plt.title("Lasso from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - -plt.show() -\epycod - -It is quite striking how LASSO breaks the symmetry of the coupling -constant as opposed to ridge and OLS. We get a sparse solution with -$J_{j, j + 1} = -1$. - - - -% !split -\subsection{Performance as function of the regularization parameter} - -We see how the different models perform for a different set of values for $\lambda$. - - -\bpycod -lambdas = np.logspace(-4, 5, 10) - -train_errors = { - "ols_sk": np.zeros(lambdas.size), - "ridge_sk": np.zeros(lambdas.size), - "lasso_sk": np.zeros(lambdas.size) -} - -test_errors = { - "ols_sk": np.zeros(lambdas.size), - "ridge_sk": np.zeros(lambdas.size), - "lasso_sk": np.zeros(lambdas.size) -} - -plot_counter = 1 - -fig = plt.figure(figsize=(32, 54)) - -for i, _lambda in enumerate(tqdm.tqdm(lambdas)): - for key, method in zip( - ["ols_sk", "ridge_sk", "lasso_sk"], - [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)] - ): - method = method.fit(X_train, y_train) - - train_errors[key][i] = method.score(X_train, y_train) - test_errors[key][i] = method.score(X_test, y_test) - - omega = method.coef_.reshape(L, L) - - plt.subplot(10, 5, plot_counter) - plt.imshow(omega, **cmap_args) - plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda)) - plot_counter += 1 - -plt.show() -\epycod - -We see that LASSO reaches a good solution for low -values of $\lambda$, but will "wither" when we increase $\lambda$ too -much. Ridge is more stable over a larger range of values for -$\lambda$, but eventually also fades away. - -% !split -\subsection{Finding the optimal value of $\lambda$} - -To determine which value of $\lambda$ is best we plot the accuracy of -the models when predicting the training and the testing set. We expect -the accuracy of the training set to be quite good, but if the accuracy -of the testing set is much lower this tells us that we might be -subject to an overfit model. The ideal scenario is an accuracy on the -testing set that is close to the accuracy of the training set. - - -\bpycod -fig = plt.figure(figsize=(20, 14)) - -colors = { - "ols_sk": "r", - "ridge_sk": "y", - "lasso_sk": "c" -} - -for key in train_errors: - plt.semilogx( - lambdas, - train_errors[key], - colors[key], - label="Train {0}".format(key), - linewidth=4.0 - ) - -for key in test_errors: - plt.semilogx( - lambdas, - test_errors[key], - colors[key] + "--", - label="Test {0}".format(key), - linewidth=4.0 - ) -plt.legend(loc="best", fontsize=18) -plt.xlabel(r"$\lambda$", fontsize=18) -plt.ylabel(r"$R^2$", fontsize=18) -plt.tick_params(labelsize=18) -plt.show() -\epycod - -From the above figure we can see that LASSO with $\lambda = 10^{-2}$ -achieves a very good accuracy on the test set. This by far surpasses the -other models for all values of $\lambda$. - - - -% !split -\subsection{Further Exercises} - -\paragraph{Exercise 1.} -We will 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). -\bpycod -x = np.random.rand(100,1) -y = 5*x*x+0.1*np.random.randn(100,1) -\epycod - -\begin{enumerate} -\item Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial. - -\item Use thereafter \textbf{scikit-learn} (see again the examples in the regression slides) and compare with your own code. - -\item Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as -\end{enumerate} - -\noindent -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] - -You can use the functionality included in scikit-learn. If you feel -for it, you can use your own program and define functions which -compute the above two functions. Discuss the meaning of these -results. Try also to vary the coefficient in front of the added -stochastic noise term and discuss the quality of the fits. - - - - -\paragraph{Exercise 2, variance of the parameters $\beta$ in linear regression.} -Show that the variance of the parameters $\beta$ in the linear regression method (chapter 3, equation (3.8) of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}) is given as - -\[ -\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, -\] -with -\[ -\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, -\] -where we have assumed that we fit a function of degree $p-1$ (for example a polynomial in $x$). - - - -\paragraph{Exercise 3.} -This exercise is a continuation of exercise 1. 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. You can use the code under the Regression as an example on how to use the Ridge and the Lasso 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). -\bpycod -x = np.random.rand(100,1) -y = 5*x*x+0.1*np.random.randn(100,1) -\epycod - -\begin{enumerate} -\item Write your own code for the Ridge method and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 1. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. - -\item Repeat the above but using the functionality of \textbf{scikit-learn}. Compare your code with the results from \textbf{scikit-learn}. Remember to run with the same random numbers for generating $x$ and $y$. - -\item Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parametrizing 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 that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$) or use the functionality of \textbf{scikit-learn} and compute their variances. Discuss the results of these variances as functions - -\item Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results. - -\item Try to implement the cross-validation as well. - -\item Finally, using \textbf{scikit-learn} or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as -\end{enumerate} - -\noindent -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] -Discuss these quantities as functions of the variable $\lambda$ in the Ridge and Lasso regression methods. - -\paragraph{Exercise 4.} -We will study how -to fit polynomials to a specific two-dimensional function called -\href{{http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf}}{Franke's -function}. This -is a function which has been widely used when testing various interpolation and fitting -algorithms. Furthermore, after having established the model and the -method, we will employ resamling techniques such as the cross-validation and/or -the bootstrap methods, in order to perform a proper assessment of our models. - - -The Franke function, which is a weighted sum of four exponentials reads as follows -\begin{align*} -f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ -&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. -\end{align*} - -The function will be defined for $x,y\in [0,1]$. Our first step will -be to perform an OLS regression analysis of this function, trying out -a polynomial fit with an $x$ and $y$ dependence of the form $[x, y, -x^2, y^2, xy, \dots]$. We will also include cross-validation and -bootstrap as resampling techniques. As in homeworks 1 and 2, we -can use a uniform distribution to set up the arrays of values for $x$ -and $y$, or as in the example below just a fix values for $x$ and $y$ with a given step size. -In this case we will have two predictors and need to fit a -function (for example a polynomial) of $x$ and $y$. Thereafter we will -repeat much of the same procedure using the the Ridge and -Lasso regression methods, introducing thus a dependence on the bias -(penalty) $\lambda$. - - -The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) -\bpycod -from mpl_toolkits.mplot3d import Axes3D -import matplotlib.pyplot as plt -from matplotlib import cm -from matplotlib.ticker import LinearLocator, FormatStrFormatter -import numpy as np -from random import random, seed - -fig = plt.figure() -ax = fig.gca(projection='3d') - -# Make data. -x = np.arange(0, 1, 0.05) -y = np.arange(0, 1, 0.05) -x, y = np.meshgrid(x,y) - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -z = FrankeFunction(x, y) - -# Plot the surface. -surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm, - linewidth=0, antialiased=False) - -# Customize the z axis. -ax.set_zlim(-0.10, 1.40) -ax.zaxis.set_major_locator(LinearLocator(10)) -ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) - -# Add a color bar which maps values to colors. -fig.colorbar(surf, shrink=0.5, aspect=5) - -plt.show() - -\epycod - - -We will thus again generate our own dataset for a function $\mathrm{FrankeFunction}(x,y)$ where -$x,y \in [0,1]$ could be defined by random numbers computed with the uniform -distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition -an added stochastic noise to this function using the normal distribution $\cal{N}(0,1)$. - -Write your own code (using either a matrix inversion or a singular value decomposition from e.g., \textbf{numpy} ) or use your code from exercises 1 and 3 -and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\beta$ by computing their variances, evaluate the Mean Squared error (MSE) -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] - -Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm -and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models. - - -Write then your own code for the Ridge method, either using matrix -inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the -previous exercise (for the same polynomials and include resampling -techniques) but now for different values of $\lambda$. Compare and -analyze your results with those obtained with standard OLS. Study the -dependence on $\lambda$ while also varying eventually the strength of -the noise in your expression for $\mathrm{FrankeFunction}(x,y)$. - -Then perform the same studies but now with Lasso regression. Use the functionalities of -\textbf{scikit-learn}. Give a critical discussion of the three methods and a -judgement of which model fits the data best. - - -% ------------------- end of main content --------------- - -% #ifdef PREAMBLE -\end{document} -% #endif - diff --git a/doc/src/Regression/Regression.tex b/doc/src/Regression/Regression.tex deleted file mode 100644 index 35dc47bdb..000000000 --- a/doc/src/Regression/Regression.tex +++ /dev/null @@ -1,3673 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% - - -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{fancyvrb} % packages needed for verbatim environments -\usepackage{minted} -\usemintedstyle{default} - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -\usepackage[framemethod=TikZ]{mdframed} - -% --- begin definitions of admonition environments --- - -% --- end of definitions of admonition environments --- - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Jul 22, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection*{Why Linear Regression (aka Ordinary Least Squares and family)} - -Fitting a continuous function with linear parameterization in terms of the parameters $\bm{\beta}$. -\begin{itemize} -\item Method of choice for fitting a continuous function! - -\item Gives an excellent introduction to central Machine Learning features with \textbf{understandable pedagogical} links to other methods like \textbf{Neural Networks}, \textbf{Support Vector Machines} etc - -\item Analytical expression for the fitting parameters $\bm{\beta}$ - -\item Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more - -\item Analytical relation with probabilistic interpretations - -\item Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics - -\item Easy to code! And links well with classification problems and logistic regression and neural networks - -\item Allows for \textbf{easy} hands-on understanding of gradient descent methods - -\item and many more features -\end{itemize} - -\noindent -For more discussions of Ridge and Lasso regression, \href{{https://arxiv.org/abs/1509.09169}}{Wessel van Wieringen's} article is highly recommended. -Similarly, \href{{https://arxiv.org/abs/1803.08823}}{Mehta et al's article} is also recommended. - - -% !split -\subsection*{Regression analysis, overarching aims} - -% --- begin paragraph admon --- -\paragraph{} - -Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\bm{x} =[x_0, x_1,\dots, x_{n-1}]^T$. -The first variable is called the \textbf{dependent}, the \textbf{outcome} or the \textbf{response} variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable. - -A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$, that is the conditional distribution for $\bm{y}$ with a given $\bm{x}$. The estimation of $p(\bm{y}\vert \bm{x})$ is made using a data set with -\begin{itemize} -\item $n$ cases $i = 0, 1, 2, \dots, n-1$ - -\item Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ - -\item $p$ so-called explanatory (independent or predictor) variables $\bm{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}]$ with $i = 0, 1, 2, \dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. -\end{itemize} - -\noindent - The goal of the regression analysis is to extract/exploit relationship between $\bm{y}$ and $\bm{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. -% --- end paragraph admon --- - - - -% !split -\subsection*{Regression analysis, overarching aims II} - -% --- begin paragraph admon --- -\paragraph{} - - -Consider an experiment in which $p$ characteristics of $n$ samples are -measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix -$\mathbf{X}$. - -The matrix $\mathbf{X}$ is called the \emph{design -matrix}. Additional information of the samples is available in the -form of $\bm{y}$ (also as above). The variable $\bm{y}$ is -generally referred to as the \emph{response variable}. The aim of -regression analysis is to explain $\bm{y}$ in terms of -$\bm{X}$ through a functional relationship like $y_i = -f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of -$f(\cdot)$ is available, it is common to assume a linear relationship -between $\bm{X}$ and $\bm{y}$. This assumption gives rise to -the \emph{linear regression model} where $\bm{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T}$ are the \emph{regression parameters}. - -Linear regression gives us a set of analytical equations for the parameters $\beta_j$. -% --- end paragraph admon --- - - - - - -% !split -\subsection*{Examples} - -% --- begin paragraph admon --- -\paragraph{} -In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$, -consider the model we discussed for describing nuclear binding energies. - -There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. -Assuming -\[ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, -\] -we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms. -This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a -$p\times n$ matrix $\bm{X}$. - -Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called \href{{https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub}}{credit card default data from Taiwan}. The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \times 30000$ -% --- end paragraph admon --- - - - - - - - -% !split -\subsection*{General linear models} - -% --- begin paragraph admon --- -\paragraph{} -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\bm{y}=[y_0,y_1,\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\bm{x}=[x_0,x_1,\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. - -Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is -\[ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, -\] -where $\epsilon_i$ is the error in our approximation. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Rewriting the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} -For every set of values $y_i,x_i$ we have thus the corresponding set of equations -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -% --- end paragraph admon --- - - - - -% !split -\subsection*{Rewriting the fitting procedure as a linear algebra problem, more details} - -% --- begin paragraph admon --- -\paragraph{} -Defining the vectors -\[ -\bm{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -\] -and -\[ -\bm{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -\] -and -\[ -\bm{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -\] -and the design matrix -\[ -\bm{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -\] -we can rewrite our equations as -\[ -\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. -\] -The above design matrix is called a \href{{https://en.wikipedia.org/wiki/Vandermonde_matrix}}{Vandermonde matrix}. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Generalizing the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} - -We are obviously not limited to the above polynomial expansions. We -could replace the various powers of $x$ with elements of Fourier -series or instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j -x_i)}$, or time series or other orthogonal functions. For every set -of values $y_i,x_i$ we can then generalize the equations to - -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} - -\textbf{Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!} -% --- end paragraph admon --- - - - - -% !split -\subsection*{Generalizing the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} -We redefine in turn the matrix $\bm{X}$ as -\[ -\bm{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -\] -and without loss of generality we rewrite again our equations as -\[ -\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. -\] -The left-hand side of this equation is kwown. Our error vector $\bm{\epsilon}$ and the parameter vector $\bm{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? -% --- end paragraph admon --- - - - - -% !split -\subsection*{Optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -We have defined the matrix $\bm{X}$ via the equations -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} - -As we noted above, we stayed with a system with the design matrix - $\bm{X}\in {\mathbb{R}}^{n\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define -our matrix as $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Our model for the nuclear binding energies} - -In our \href{{https://compphysics.github.io/MachineLearningMSU/doc/pub/Introduction/html/Introduction.html}}{introductory notes} we looked at the so-called \href{{https://en.wikipedia.org/wiki/Semi-empirical_mass_formula}}{liguid drop model}. Let us remind ourselves about what we did by looking at the code. - -We restate the parts of the code we are most interested in. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from IPython.display import display -import os - -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("MassEval2016.dat"),'r') - - -# Read the experimental data with Pandas -Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), - names=('N', 'Z', 'A', 'Element', 'Ebinding'), - widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), - header=39, - index_col=False) - -# Extrapolated values are indicated by '#' in place of the decimal place, so -# the Ebinding column won't be numeric. Coerce to float and drop these entries. -Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') -Masses = Masses.dropna() -# Convert from keV to MeV. -Masses['Ebinding'] /= 1000 - -# Group the DataFrame by nucleon number, A. -Masses = Masses.groupby('A') -# Find the rows of the grouped DataFrame with the maximum binding energy. -Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) -A = Masses['A'] -Z = Masses['Z'] -N = Masses['N'] -Element = Masses['Element'] -Energies = Masses['Ebinding'] - -# Now we set up the design matrix X -X = np.zeros((len(A),5)) -X[:,0] = 1 -X[:,1] = A -X[:,2] = A**(2.0/3.0) -X[:,3] = A**(-1.0/3.0) -X[:,4] = A**(-1.0) -# Then nice printout using pandas -DesignMatrix = pd.DataFrame(X) -DesignMatrix.index = A -DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A'] -display(DesignMatrix) -\end{minted} - -With $\bm{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as -\[ -\bm{\tilde{y}}= \bm{X}\bm{\beta}, -\] -throughout these lectures. - - -% !split -\subsection*{Optimizing our parameters, more details} - -% --- begin paragraph admon --- -\paragraph{} -With the above we use the design matrix to define the approximation $\bm{\tilde{y}}$ via the unknown quantity $\bm{\beta}$ as -\[ -\bm{\tilde{y}}= \bm{X}\bm{\beta}, -\] -and in order to find the optimal parameters $\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parameterized values $\tilde{y}_i$, namely -\[ -C(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, -\] -or using the matrix $\bm{X}$ and in a more compact matrix-vector notation as -\[ -C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}^T\bm{\beta}\right)^T\left(\bm{y}-\bm{X}^T\bm{\beta}\right)\right\}. -\] -This function is one possible way to define the so-called cost function. - - - -It is also common to define -the function $Q$ as - -\[ -C(\bm{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, -\] -since when taking the first derivative with respect to the unknown parameters $\beta$, the factor of $2$ cancels out. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} - -The function -\[ -C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}, -\] -can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises) -\[ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -\] - -where $\langle y_i \rangle$ is the mean value. Keep in mind also that -till now we have treated $y_i$ as the exact value. Normally, the -response (dependent or outcome) variable $y_i$ the outcome of a -numerical experiment or another type of experiment and is thus only an -approximation to the true value. It is then always accompanied by an -error estimate, often limited to a statistical error estimate given by -the standard deviation discussed earlier. In the discussion here we -will treat $y_i$ as our exact value for the response variable. - -In order to find the parameters $\beta_i$ we will then minimize the spread of $C(\bm{\beta})$, that is we are going to solve the problem -\[ -{\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\}. -\] -In practical terms it means we will require -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -\] -which results in -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -\] -or in a matrix-vector form as -\[ -\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right). -\] -% --- end paragraph admon --- - - - - -% !split -\subsection*{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -We can rewrite -\[ -\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right), -\] -as -\[ -\bm{X}^T\bm{y} = \bm{X}^T\bm{X}\bm{\beta}, -\] -and if the matrix $\bm{X}^T\bm{X}$ is invertible we have the solution -\[ -\bm{\beta} =\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] - -We note also that since our design matrix is defined as $\bm{X}\in -{\mathbb{R}}^{n\times p}$, the product $\bm{X}^T\bm{X} \in -{\mathbb{R}}^{p\times p}$. In the above case we have that $p \ll n$, -in our case $p=5$ meaning that we end up with inverting a small -$5\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional -matrices to invert. The methods discussed here and for many other -supervised learning algorithms like classification with logistic -regression or support vector machines, exhibit dimensionalities which -allow for the usage of direct linear algebra methods such as \textbf{LU} decomposition or \textbf{Singular Value Decomposition} (SVD) for finding the inverse of the matrix -$\bm{X}^T\bm{X}$. -% --- end paragraph admon --- - - - -% !split -\subsection*{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -The residuals $\bm{\epsilon}$ are in turn given by -\[ -\bm{\epsilon} = \bm{y}-\bm{\tilde{y}} = \bm{y}-\bm{X}\bm{\beta}, -\] -and with -\[ -\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, -\] -we have -\[ -\bm{X}^T\bm{\epsilon}=\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, -\] -meaning that the solution for $\bm{\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. -% --- end paragraph admon --- - - - - -Let us now return to our nuclear binding energies and simply code the above equations. - -% !split -\subsection*{Own code for Ordinary Least Squares} - -It is rather straightforward to implement the matrix inversion and obtain the parameters $\bm{\beta}$. After having defined the matrix $\bm{X}$ we simply need to -write -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# matrix inversion to find beta -beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies) -# and then make the prediction -ytilde = X @ beta -\end{minted} -Alternatively, you can use the least squares functionality in \textbf{Numpy} as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fit = np.linalg.lstsq(X, Energies, rcond =None)[0] -ytildenp = np.dot(fit,X.T) -\end{minted} - -And finally we plot our fit with and compare with data -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -Masses['Eapprox'] = ytilde -# Generate a plot comparing the experimental with the fitted values values. -fig, ax = plt.subplots() -ax.set_xlabel(r'$A = N + Z$') -ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') -ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, - label='Ame2016') -ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', - label='Fit') -ax.legend() -save_fig("Masses2016OLS") -plt.show() -\end{minted} - -% !split -\subsection*{Adding error analysis and training set up} - -We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. -Since we are not using _Scikit-Learn here we can define our own $R2$ function as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) -\end{minted} -and we would be using it as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -print(R2(Energies,ytilde)) -\end{minted} - -We can easily add our \textbf{MSE} score as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -print(MSE(Energies,ytilde)) -\end{minted} -and finally the relative error as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def RelativeError(y_data,y_model): - return abs((y_data-y_model)/y_data) -print(RelativeError(Energies, ytilde)) -\end{minted} - - - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -Normally, the response (dependent or outcome) variable $y_i$ is the -outcome of a numerical experiment or another type of experiment and is -thus only an approximation to the true value. It is then always -accompanied by an error estimate, often limited to a statistical error -estimate given by the standard deviation discussed earlier. In the -discussion here we will treat $y_i$ as our exact value for the -response variable. - -Introducing the standard deviation $\sigma_i$ for each measurement -$y_i$, we define now the $\chi^2$ function (omitting the $1/n$ term) -as - -\[ -\chi^2(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\frac{1}{\bm{\Sigma^2}}\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, -\] -where the matrix $\bm{\Sigma}$ is a diagonal matrix with $\sigma_i$ as matrix elements. -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -In order to find the parameters $\beta_i$ we will then minimize the spread of $\chi^2(\bm{\beta})$ by requiring -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -\] -which results in -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -\] -or in a matrix-vector form as -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right). -\] -where we have defined the matrix $\bm{A} =\bm{X}/\bm{\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\sigma_i$ and the vector $\bm{b}$ with elements $b_i = y_i/\sigma_i$. -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -We can rewrite -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right), -\] -as -\[ -\bm{A}^T\bm{b} = \bm{A}^T\bm{A}\bm{\beta}, -\] -and if the matrix $\bm{A}^T\bm{A}$ is invertible we have the solution -\[ -\bm{\beta} =\left(\bm{A}^T\bm{A}\right)^{-1}\bm{A}^T\bm{b}. -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -If we then introduce the matrix -\[ -\bm{H} = \left(\bm{A}^T\bm{A}\right)^{-1}, -\] -we have then the following expression for the parameters $\beta_j$ (the matrix elements of $\bm{H}$ are $h_{ij}$) -\[ -\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} -\] -We state without proof the expression for the uncertainty in the parameters $\beta_j$ as (we leave this as an exercise) -\[ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -\] -resulting in -\[ -\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} -The first step here is to approximate the function $y$ with a first-order polynomial, that is we write -\[ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -\] -By computing the derivatives of $\chi^2$ with respect to $\beta_0$ and $\beta_1$ show that these are given by -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -\] -and -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -For a linear fit (a first-order polynomial) we don't need to invert a matrix!! -Defining -\[ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -\] - -\[ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -\] - -\[ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -\] - -\[ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -\] - -\[ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -\] - -we obtain - -\[ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -\] - -\[ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -\] - -This approach (different linear and non-linear regression) suffers -often from both being underdetermined and overdetermined in the -unknown coefficients $\beta_i$. A better approach is to use the -Singular Value Decomposition (SVD) method discussed below. Or using -Lasso and Ridge regression. See below. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Fitting an Equation of State for Dense Nuclear Matter} - -Before we continue, let us introduce yet another example. We are going to fit the -nuclear equation of state using results from many-body calculations. -The equation of state we have made available here, as function of -density, has been derived using modern nucleon-nucleon potentials with -\href{{https://www.sciencedirect.com/science/article/pii/S0370157399001106}}{the addition of three-body -forces}. This -time the file is presented as a standard \textbf{csv} file. - -The beginning of the Python code here is similar to what you have seen before, -with the same initializations and declarations. We use also \textbf{pandas} -again, rather extensively in order to organize our data. - -The difference now is that we use \textbf{Scikit-Learn's} regression tools -instead of our own matrix inversion implementation. Furthermore, we -sneak in \textbf{Ridge} regression (to be discussed below) which includes a -hyperparameter $\lambda$, also to be explained below. - -% !split -\subsection*{The code} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import matplotlib.pyplot as plt -import sklearn.linear_model as skl -from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error - -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organize the data into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops -X = np.zeros((len(Density),4)) -X[:,3] = Density**(4.0/3.0) -X[:,2] = Density -X[:,1] = Density**(2.0/3.0) -X[:,0] = 1 - -# We use now Scikit-Learn's linear regressor and ridge regressor -# OLS part -clf = skl.LinearRegression().fit(X, Energies) -ytilde = clf.predict(X) -EoS['Eols'] = ytilde -# The mean squared error -print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(Energies, ytilde)) -# Mean absolute error -print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde)) -print(clf.coef_, clf.intercept_) - -# The Ridge regression with a hyperparameter lambda = 0.1 -_lambda = 0.1 -clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies) -yridge = clf_ridge.predict(X) -EoS['Eridge'] = yridge -# The mean squared error -print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(Energies, yridge)) -# Mean absolute error -print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge)) -print(clf_ridge.coef_, clf_ridge.intercept_) - -fig, ax = plt.subplots() -ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$') -ax.set_ylabel(r'Energy per particle') -ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2, - label='Theoretical data') -ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m', - label='OLS') -ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g', - label='Ridge $\lambda = 0.1$') -ax.legend() -save_fig("EoSfitting") -plt.show() -\end{minted} - -The above simple polynomial in density $\rho$ gives an excellent fit -to the data. Can you give an interpretation of the various powers of $\rho$? - -We note also that there is a small deviation between the -standard OLS and the Ridge regression at higher densities. We discuss this in more detail -below. - - -% !split -\subsection*{Splitting our Data in Training and Test data} - -It is normal in essentially all Machine Learning studies to split the -data in a training set and a test set (sometimes also an additional -validation set). \textbf{Scikit-Learn} has an own function for this. There -is no explicit recipe for how much data should be included as training -data and say test data. An accepted rule of thumb is to use -approximately $2/3$ to $4/5$ of the data as training data. We will -postpone a discussion of this splitting to the end of these notes and -our discussion of the so-called \textbf{bias-variance} tradeoff. Here we -limit ourselves to repeat the above equation of state fitting example -but now splitting the data into a training set and a test set. - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organized into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops -X = np.zeros((len(Density),5)) -X[:,0] = 1 -X[:,1] = Density**(2.0/3.0) -X[:,2] = Density -X[:,3] = Density**(4.0/3.0) -X[:,4] = Density**(5.0/3.0) -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) -# matrix inversion to find beta -beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train) -# and then make the prediction -ytilde = X_train @ beta -print("Training R2") -print(R2(y_train,ytilde)) -print("Training MSE") -print(MSE(y_train,ytilde)) -ypredict = X_test @ beta -print("Test R2") -print(R2(y_test,ypredict)) -print("Test MSE") -print(MSE(y_test,ypredict)) -\end{minted} - - -% !split -\subsection*{The singular value decomposition} - - -% --- begin paragraph admon --- -\paragraph{} - -The examples we have looked at so far are cases where we normally can -invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion as we -did both for the masses and the fitting of the equation of state, -leads to row vectors of the design matrix which are essentially -orthogonal due to the polynomial character of our model. This may -however not the be case in general and a standard matrix inversion -algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit -the coupling constant of the widely used Ising model. -There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. - -This is given by the \textbf{Singular Value Decomposition} algorithm, perhaps -the most powerful linear algebra algorithm. Let us look at a -different example where we may have problems with the standard matrix -inversion algorithm. Thereafter we dive into the math of the SVD. -% --- end paragraph admon --- - - - -% !split -\subsection*{The Ising model} - -The one-dimensional Ising model with nearest neighbor interaction, no -external field and a constant coupling constant $J$ is given by - -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\end{align} - -where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins -in the system is determined by $L$. For the one-dimensional system -there is no phase transition. - -We will look at a system of $L = 40$ spins with a coupling constant of -$J = 1$. To get enough training data we will generate 10000 states -with their respective energies. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import make_axes_locatable -import seaborn as sns -import scipy.linalg as scl -from sklearn.model_selection import train_test_split -import tqdm -sns.set(color_codes=True) -cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') - -L = 40 -n = int(1e4) - -spins = np.random.choice([-1, 1], size=(n, L)) -J = 1.0 - -energies = np.zeros(n) - -for i in range(n): - energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) -\end{minted} - -Here we use ordinary least squares -regression to predict the energy for the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use linear regression to fit a value for -the coupling constant to achieve this. - -% !split -\subsection*{Reformulating the problem to suit regression} - -A more general form for the one-dimensional Ising model is - -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\end{align} - -Here we allow for interactions beyond the nearest neighbors and a state dependent -coupling constant. This latter expression can be formulated as -a matrix-product -\begin{align} - \bm{H} = \bm{X} J, -\end{align} - -where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the -elements $-J_{jk}$. This form of writing the energy fits perfectly -with the form utilized in linear regression, that is - -\begin{align} - \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}, -\end{align} - -We split the data in training and test data as discussed in the previous example - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X = np.zeros((n, L ** 2)) -for i in range(n): - X[i] = np.outer(spins[i], spins[i]).ravel() -y = energies -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) -\end{minted} - -% !split -\subsection*{Linear regression} - -In the ordinary least squares method we choose the cost function - -\begin{align} - C(\bm{X}, \bm{\beta})= \frac{1}{n}\left\{(\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y})\right\}. -\end{align} - -We then find the extremal point of $C$ by taking the derivative with respect to $\bm{\beta}$ as discussed above. -This yields the expression for $\bm{\beta}$ to be - -\[ - \bm{\beta} = \frac{\bm{X}^T \bm{y}}{\bm{X}^T \bm{X}}, -\] - -which immediately imposes some requirements on $\bm{X}$ as there must exist -an inverse of $\bm{X}^T \bm{X}$. If the expression we are modeling contains an -intercept, i.e., a constant term, we must make sure that the -first column of $\bm{X}$ consists of $1$. We do this here - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X_train_own = np.concatenate( - (np.ones(len(X_train))[:, np.newaxis], X_train), - axis=1 -) -X_test_own = np.concatenate( - (np.ones(len(X_test))[:, np.newaxis], X_test), - axis=1 -) -\end{minted} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray: - return scl.inv(x.T @ x) @ (x.T @ y) -beta = ols_inv(X_train_own, y_train) -\end{minted} - - -% !split -\subsection*{Singular Value decomposition} - -Doing the inversion directly turns out to be a bad idea since the matrix -$\bm{X}^T\bm{X}$ is singular. An alternative approach is to use the \textbf{singular -value decomposition}. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for $\bm{\beta}$ as - -\[ - \bm{\beta} = \bm{X}^{+}\bm{y}, -\] - -where the pseudoinverse of $\bm{X}$ is given by - -\[ - \bm{X}^{+} = \frac{\bm{X}^T}{\bm{X}^T\bm{X}}. -\] - -Using singular value decomposition we can decompose the matrix $\bm{X} = \bm{U}\bm{\Sigma} \bm{V}^T$, -where $\bm{U}$ and $\bm{V}$ are orthogonal(unitary) matrices and $\bm{\Sigma}$ contains the singular values (more details below). -where $X^{+} = V\Sigma^{+} U^T$. This reduces the equation for -$\omega$ to -\begin{align} - \bm{\beta} = \bm{V}\bm{\Sigma}^{+} \bm{U}^T \bm{y}. -\end{align} - -Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as $\mathcal{O}(n^3)$, where $n$ is the number of elements in a -general matrix. Instead, doing $QR$-factorization and solving the -linear system as an equation would reduce this down to -$\mathcal{O}(n^2)$ operations. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray: - u, s, v = scl.svd(x) - return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y -\end{minted} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -beta = ols_svd(X_train_own,y_train) -\end{minted} - -When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -J = beta[1:].reshape(L, L) -\end{minted} - -A way of looking at the coefficients in $J$ is to plot the matrices as images. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J, **cmap_args) -plt.title("OLS", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) -plt.show() -\end{minted} -It is interesting to note that OLS -considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as -valid matrix elements for $J$. -In our discussion below on hyperparameters and Ridge and Lasso regression we will see that -this problem can be removed, partly and only with Lasso regression. - -In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? - - -% !split -\subsection*{Linear Regression Problems} - -One of the typical problems we encounter with linear regression, in particular -when the matrix $\bm{X}$ (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of $\bm{X}$ -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} - -The columns of $\bm{X}$ are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of $\mathbf{X}$ is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. - -Super-collinearity of an $(n \times p)$-dimensional design matrix $\mathbf{X}$ implies -that the inverse of the matrix $\bm{X}^T\bm{x}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -\begin{align*} -\bm{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -We see easily that $\mbox{det}(\bm{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined. -This is equivalent to saying that the matrix $\bm{X}$ has at least an eigenvalue which is zero. - - -% !split -\subsection*{Fixing the singularity} - -If our design matrix $\bm{X}$ which enters the linear regression problem -\begin{align} -\bm{\beta} & = (\bm{X}^{T} \bm{X})^{-1} \bm{X}^{T} \bm{y}, -\end{align} -has linearly dependent column vectors, we will not be able to compute the inverse -of $\bm{X}^T\bm{X}$ and we cannot find the parameters (estimators) $\beta_i$. -The estimators are only well-defined if $(\bm{X}^{T}\bm{X})^{-1}$ exits. -This is more likely to happen when the matrix $\bm{X}$ is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters $\beta_i$ cannot be estimated. - -A cheap \emph{ad hoc} approach is simply to add a small diagonal component to the matrix to invert, that is we change -\[ -\bm{X}^{T} \bm{X} \rightarrow \bm{X}^{T} \bm{X}+\lambda \bm{I}, -\] -where $\bm{I}$ is the identity matrix. When we discuss \textbf{Ridge} regression this is actually what we end up evaluating. The parameter $\lambda$ is called a hyperparameter. More about this later. - - - -% !split -\subsection*{Basic math of the SVD} - - -From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is -a so-called \href{{https://en.wikipedia.org/wiki/Normal_matrix}}{normal matrix}, that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$ -we have $\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ or if $\bm{X}\in {\mathbb{C}}^{n\times n}$ we have $\bm{X}\bm{X}^{\dagger}=\bm{X}^{\dagger}\bm{X}$. -The matrix has then a set of eigenpairs - -\[ -(\lambda_1,\bm{u}_1),\dots, (\lambda_n,\bm{u}_n), -and the eigenvalues are given by the diagonal matrix -\[ -\bm{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). -\] -The matrix $\bm{X}$ can be written in terms of an orthogonal/unitary transformation $\bm{U}$ -\[ -\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T, -\] -with $\bm{U}\bm{U}^T=\bm{I}$ or $\bm{U}\bm{U}^{\dagger}=\bm{I}$. - -Not all square matrices are diagonalizable. A matrix like the one discussed above -\[ -\bm{X} = \begin{bmatrix} -1& -1 \\ -1& -1\\ -\end{bmatrix} -\] -is not diagonalizable, it is a so-called \href{{https://en.wikipedia.org/wiki/Defective_matrix}}{defective matrix}. It is easy to see that the condition -$\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ is not fulfilled. - - -% !split -\subsection*{The SVD, a Fantastic Algorithm} - - -However, and this is the strength of the SVD algorithm, any general -matrix $\bm{X}$ can be decomposed in terms of a diagonal matrix and -two orthogonal/unitary matrices. The \href{{https://en.wikipedia.org/wiki/Singular_value_decomposition}}{Singular Value Decompostion -(SVD) theorem} -states that a general $m\times n$ matrix $\bm{X}$ can be written in -terms of a diagonal matrix $\bm{\Sigma}$ of dimensionality $n\times n$ -and two orthognal matrices $\bm{U}$ and $\bm{V}$, where the first has -dimensionality $m \times m$ and the last dimensionality $n\times n$. -We have then - -\[ -\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T -\] - -As an example, the above defective matrix can be decomposed as - -\[ -\bm{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T, -\] - -with eigenvalues $\sigma_1=2$ and $\sigma_2=0$. -The SVD exits always! - - -% !split -\subsection*{Another Example} - -Consider the following matrix which can be SVD decomposed as - -\[ -\bm{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T. -\] - -This is a $3\times 2$ matrix which is decomposed in terms of a -$3\times 3$ matrix $\bm{U}$, and a $2\times 2$ matrix $\bm{V}$. It is easy to see -that $\bm{U}$ and $\bm{V}$ are orthogonal (how?). - -And the SVD -decomposition (singular values) gives eigenvalues -$\sigma_i\geq\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=2$, the -eigenvalues (singular values) are zero. - -In the general case, where our design matrix $\bm{X}$ has dimension -$n\times p$, the matrix is thus decomposed into an $n\times n$ -orthogonal matrix $\bm{U}$, a $p\times p$ orthogonal matrix $\bm{V}$ -and a diagonal matrix $\bm{\Sigma}$ with $r=\mathrm{min}(n,p)$ -singular values $\sigma_i\lg 0$ on the main diagonal and zeros filling -the rest of the matrix. There are at most $p$ singular values -assuming that $n > p$. In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have $p > n$. These are often cases that lead to -near singular or singular matrices. - -The columns of $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors. - -% !split -\subsection*{Economy-size SVD} - -If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n -\times n$. The last $n-p$ columns of $\bm{U}$ become however -irrelevant in our calculations since they are multiplied with the -zeros in $\bm{\Sigma}$. - -The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, $\bm{\Sigma}$, along with the columns -in either $\bm{U}$ or $\bm{V}$ that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. - -If $n > p$, we keep only the first $p$ columns of $\bm{U}$ and $\bm{\Sigma}$ has dimension $p\times p$. -If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\Sigma}$ has dimension $n\times n$. -The $n=p$ case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. - -% !split -\subsection*{Mathematical Properties} - -There are several interesting mathematical properties which will be -relevant when we are going to discuss the differences between say -ordinary least squares (OLS) and \textbf{Ridge} regression. - -We have from OLS that the parameters of the linear approximation are given by -\[ -\bm{\tilde{y}} = \bm{X}\bm{\beta} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] - -The matrix to invert can be rewritten in terms of our SVD decomposition as - -\[ -\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T. -\] -Using the orthogonality properties of $\bm{U}$ we have - -\[ -\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T = \bm{V}\bm{D}\bm{V}^T, -\] -with $\bm{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. - -This means that -\[ -(\bm{X}^T\bm{X})\bm{V} = \bm{V}\bm{D}, -\] -that is the eigenvectors of $(\bm{X}^T\bm{X})$ are given by the columns of the right singular matrix of $\bm{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that -\[ -(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}, -\] -that is, the eigenvectors of $(\bm{X}\bm{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. - -Going back to our OLS equation we have -\[ -\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}. -\] -We will come back to this expression when we discuss Ridge regression. - - -% !split -\subsection*{Ridge and LASSO Regression} - -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_{\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\}. -\] -or we can state it as -\[ -{\displaystyle \min_{\bm{\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 \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, -\] -where we have used the definition of a norm-2 vector, that is -\[ -\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. -\] - -By minimizing the above equation with respect to the parameters -$\bm{\beta}$ we could then obtain an analytical expression for the -parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by -defining a new cost function to be optimized, that is - -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 -\] - -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. By defining - -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, -\] - -we have a new optimization equation -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\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 \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. -\] - - -% !split -\subsection*{More on Ridge Regression} - -Using the matrix-vector expression for Ridge regression, - -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, -\] - -by taking the derivatives with respect to $\bm{\beta}$ we obtain then -a slightly modified matrix inversion problem which for finite values -of $\lambda$ does not suffer from singularity problems. We obtain - -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, -\] - -with $\bm{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. - -We see that Ridge regression is nothing but the standard -OLS with a modified diagonal term added to $\bm{X}^T\bm{X}$. The -consequences, in particular for our discussion of the bias-variance -are rather interesting. - -Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had -\[ -(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}. -\] - -We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as -\[ -\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y} -\] - - -For Ridge regression this becomes - -\[ -\bm{X}\bm{\beta}^{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, -\] - -with the vectors $\bm{u}_j$ being the columns of $\bm{U}$. - -% !split -\subsection*{Interpreting the Ridge results} - -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 $\bm{y}$ with respect to the -orthonormal basis $\bm{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}$. - -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. -Actually, calculating the variance of $\bm{X}\bm{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$. -With a parameter $\lambda$ we can thus shrink the role of specific parameters. - - -% !split -\subsection*{More interpretations} - -For the sake of simplicity, let us assume that the design matrix is orthonormal, that is - -\[ -\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. -\] - -In this case the standard OLS results in -\[ -\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, -\] - -and - -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\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. - -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, \href{{https://arxiv.org/abs/1509.09169}}{Wessel van Wieringen's} article is highly recommended. -Similarly, \href{{https://arxiv.org/abs/1803.08823}}{Mehta et al's article} is also recommended. - -% !split -\subsection*{Where are we going?} - -Before we proceed, we need to rethink what we have been doing. In our -eager to fit the data, we have omitted several important elements in -our regression analysis. In what follows we will -\begin{enumerate} -\item look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff - -\item introduce resampling techniques like cross-validation, bootstrapping and jackknife and more -\end{enumerate} - -\noindent -This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. - - - - - -% !split -\subsection*{Resampling methods} - -% --- begin paragraph admon --- -\paragraph{} -Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. -% --- end paragraph admon --- - - - -% !split -\subsection*{Resampling approaches can be computationally expensive} - -% --- begin paragraph admon --- -\paragraph{} - -Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. -% --- end paragraph admon --- - - - -% !split -\subsection*{Why resampling methods ?} - -% --- begin paragraph admon --- -\paragraph{Statistical analysis.} - -\begin{itemize} -\item Our simulations can be treated as \emph{computer experiments}. This is particularly the case for Monte Carlo methods - -\item The results can be analysed with the same statistical tools as we would use analysing experimental data. - -\item As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. -\end{itemize} - -\noindent -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistical analysis} - -% --- begin paragraph admon --- -\paragraph{} - -\begin{itemize} -\item As in other experiments, many numerical experiments have two classes of errors: -\begin{itemize} - - \item Statistical errors - - \item Systematical errors - -\end{itemize} - -\noindent -\item Statistical errors can be estimated using standard tools from statistics - -\item Systematical errors are method specific and must be treated differently from case to case. -\end{itemize} - -\noindent -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -The \emph{probability distribution function (PDF)} is a function -$p(x)$ on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of $X$ occur: -\[ -p(x) = \mathrm{prob}(X=x) -\] -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us -the \emph{density} of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval $[a,\,b]$ is then just the integral: -\[ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx -\] -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Statistics, moments} - -% --- begin paragraph admon --- -\paragraph{} -A particularly useful class of special expectation values are the -\emph{moments}. The $n$-th moment of the PDF $p$ is defined as -follows: -\[ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx -\] -The zero-th moment $\langle 1\rangle$ is just the normalization condition of -$p$. The first moment, $\langle x\rangle$, is called the \emph{mean} of $p$ -and often denoted by the letter $\mu$: -\[ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, central moments} - -% --- begin paragraph admon --- -\paragraph{} -A special version of the moments is the set of \emph{central moments}, -the n-th central moment defined as: -\[ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -\] -The zero-th and first central moments are both trivial, equal $1$ and -$0$, respectively. But the second central moment, known as the -\emph{variance} of $p$, is of particular interest. For the stochastic -variable $X$, the variance is denoted as $\sigma^2_X$ or $\mathrm{var}(X)$: -\begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\end{align} -The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle}$ is called the \emph{standard deviation} of $p$. It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the \emph{spread} of $p$ around its mean. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, covariance} - -% --- begin paragraph admon --- -\paragraph{} -Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set $\{X_i\}$ of $n$ -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF $P(x_1,\dots,x_n)$. The \emph{covariance} of two -of the stochastic variables, $X_i$ and $X_j$, is defined as follows: -\begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\label{eq:def_covariance} -\end{align} -with -\[ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, more covariance} - -% --- begin paragraph admon --- -\paragraph{} -If we consider the above covariance as a matrix $C_{ij}=\mathrm{cov}(X_i,\,X_j)$, then the diagonal elements are just the familiar -variances, $C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i)$. It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables $X_i$ and -$X_j$, ($i\neq j$): -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle \\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\end{align} -% --- end paragraph admon --- - - - - - -% !split -\subsection*{Statistics, independent variables} - -% --- begin paragraph admon --- -\paragraph{} -If $X_i$ and $X_j$ are independent, we get -$\langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle$, resulting in $\mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j)$. - -Also useful for us is the covariance of linear combinations of -stochastic variables. Let $\{X_i\}$ and $\{Y_i\}$ be two sets of -stochastic variables. Let also $\{a_i\}$ and $\{b_i\}$ be two sets of -scalars. Consider the linear combination: -\[ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j -\] -By the linearity of the expectation value -\[ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, more variance} - -% --- begin paragraph admon --- -\paragraph{} -Now, since the variance is just $\mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i)$, we get -the variance of the linear combination $U = \sum_i a_i X_i$: -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\label{eq:variance_linear_combination} -\end{equation} -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -\[ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -\] -\[ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -\] -which will become very useful in our study of the error in the mean -value of a set of measurements. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics and stochastic processes} - -% --- begin paragraph admon --- -\paragraph{} -A \emph{stochastic process} is a process that produces sequentially a -chain of values: -\[ -\{x_1, x_2,\dots\,x_k,\dots\}. -\] -We will call these -values our \emph{measurements} and the entire set as our measured -\emph{sample}. The action of measuring all the elements of a sample -we will call a stochastic \emph{experiment} since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF $p_X^{\phantom X}(x)$, where $X$ is just the formal symbol for the -stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of -trying to determine the full distribution $p$ we are often only -interested in finding the few lowest moments, like the mean -$\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Statistics and sample variables} - -% --- begin paragraph admon --- -\paragraph{} -In practical situations a sample is always of finite size. Let that -size be $n$. The expectation value of a sample, the \emph{sample mean}, is then defined as follows: -\[ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -\] -The \emph{sample variance} is: -\[ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -\] -its square root being the \emph{standard deviation of the sample}. The -\emph{sample covariance} is: -\[ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, sample variance and covariance} - -% --- begin paragraph admon --- -\paragraph{} -Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq.~(\ref{eq:def_covariance}) is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. - -These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean $\mu_X$, variance $\mathrm{var}(X)$ -and covariance $\mathrm{cov}(X,Y)$. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, law of large numbers} - -% --- begin paragraph admon --- -\paragraph{} -The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean $\mu_X^{\phantom X}$ of the chosen PDF: -\[ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} -\] -The sample mean $\bar{x}_n$ works therefore as an estimate of the true -mean $\mu_X^{\phantom X}$. - -What we need to find out is how good an approximation $\bar{x}_n$ is to -$\mu_X^{\phantom X}$. In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the \emph{error} of the sample mean, or -just sample error, and denote it by $\mathrm{err}_X^{\phantom X}$. In -practice, we will only be able to produce an \emph{estimate} of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Statistics, more on sample error} - -% --- begin paragraph admon --- -\paragraph{} -Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements $x_i$ -can be associated with its own stochastic variable $X_i$. The -stochastic variable $\overline X_n$ for the sample mean $\bar{x}_n$ is -then just a linear combination, already familiar to us: -\[ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i -\] -All the coefficients are just equal $1/n$. The PDF of $\overline X_n$, -denoted by $p_{\overline X_n}(x)$ is the desired PDF of the sample -means. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -The probability density of obtaining a sample mean $\bar x_n$ -is the product of probabilities of obtaining arbitrary values $x_1, -x_2,\dots,x_n$ with the constraint that the mean of the set $\{x_i\}$ -is $\bar x_n$: -\[ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 -\] -And in particular we are interested in its variance $\mathrm{var}(\overline X_n)$. -% --- end paragraph admon --- - - - - - -% !split -\subsection*{Statistics, central limit theorem} - -% --- begin paragraph admon --- -\paragraph{} -It is generally not possible to express $p_{\overline X_n}(x)$ in a -closed form given an arbitrary PDF $p_X^{\phantom X}$ and a number -$n$. But for the limit $n\to\infty$ it is possible to make an -approximation. The very important result is called \emph{the central limit theorem}. It tells us that as $n$ goes to infinity, -$p_{\overline X_n}(x)$ approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, $\mu_{X}^{\phantom X}$ -and $\sigma_{X}^{2}$, respectively: -\begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\label{eq:central_limit_gaussian} -\end{equation} -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, more technicalities} - -% --- begin paragraph admon --- -\paragraph{} -The desired variance -$\mathrm{var}(\overline X_n)$, i.e.~the sample error squared -$\mathrm{err}_X^2$, is given by: -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\label{eq:error_exact} -\end{equation} -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -$\mu_{X_i}^{\phantom X}$ of the stochastic variables $X_i$. To -calculate these requires that we know the true multivariate PDF of all -the $X_i$. But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the $X_i$, estimating all properties of -$X_i$ through the measurements of the sample. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -Our estimate of $\mu_{X_i}^{\phantom X}$ is then the sample mean $\bar x$ -itself, in accordance with the the central limit theorem: -\[ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x -\] -Using $\bar x$ in place of $\mu_{X_i}^{\phantom X}$ we can give an -\emph{estimate} of the covariance in Eq.~(\ref{eq:error_exact}) -\[ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, -\] -resulting in -\[ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) -\] -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics and sample variance} - -% --- begin paragraph admon --- -\paragraph{} -By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables $X_i$ -\[ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, -\] -which is approximated as -\begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\label{eq:var_estimate_i_think} -\end{equation} - -Now we can calculate an estimate of the error -$\mathrm{err}_X^{\phantom X}$ of the sample mean $\bar x_n$: -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\label{eq:error_estimate} -\end{align} -which is nothing but the sample covariance divided by the number of -measurements in the sample. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, uncorrelated results} - -% --- begin paragraph admon --- -\paragraph{} - -In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables $X_i$ are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: -\[ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), -\] -resulting in -\begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\label{eq:error_estimate_uncorrel} -\end{equation} -where in the second step we have used Eq.~(\ref{eq:var_estimate_i_think}). -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. -% --- end paragraph admon --- - - - -% !split -\subsection*{Statistics, computations} - -% --- begin paragraph admon --- -\paragraph{} -For computational purposes one usually splits up the estimate of -$\mathrm{err}_X^2$, given by Eq.~(\ref{eq:error_estimate}), into two -parts -\[ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), -\] -which equals -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k 0$. We say then that the ridge estimator is biased. - -We can also compute the variance as - -\[ -\mbox{Var}[\bm{\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 $\bm{\beta}$ goes to zero. - -With this, we can compute the difference - -\[ -\mbox{Var}[\bm{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\bm{\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 $\bm{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. - -% !split -\subsection*{Cross-validation} - -Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e.~the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. - -The setting of \textbf{original} and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the -\emph{training set}, plays the role of \textbf{original} data on which the model is -built. The second of these data sets, called the \emph{test set}, plays the -role of the \textbf{novel} data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of $\lambda$ using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. - - -% !split -\subsection*{Computationally expensive} - -The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: - -\begin{itemize} -\item The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set. - -\item In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set. -\end{itemize} - -\noindent -% !split -\subsection*{Various steps in cross-validation} - -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this $k$-fold cross-validation structures the data splitting. The -samples are divided into $k$ more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the $k$ subsets -involves a degree of randomness. This may be fully excluded when -choosing $k=n$. This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -% !split -\subsection*{How to set up the cross-validation for Ridge and/or Lasso} - -\begin{itemize} -\item Define a range of interest for the penalty parameter. - -\item Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. - -\item Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, as -\end{itemize} - -\noindent -\begin{align*} -\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T} -\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1} -\bm{X}_{-i, \ast}^{T} \bm{y}_{-i} -\end{align*} - -\begin{itemize} -\item Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. - -\item Repeat the first three steps such that each sample plays the role of the test set once. - -\item Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the \emph{cross-validated log-likelihood}. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as -\end{itemize} - -\noindent -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} - -\begin{itemize} -\item The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions. -\end{itemize} - -\noindent -% !split -\subsection*{Resampling methods: Jackknife and Bootstrap} - -Two famous -resampling methods are the \textbf{independent bootstrap} and \textbf{the jackknife}. - -The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as \textbf{the dependent bootstrap}. - -The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of $\overline{X}$ (which often is the case), then there is no -need for bootstrapping. - -% !split -\subsection*{Resampling methods: Jackknife} - -The Jackknife works by making many replicas of the estimator $\widehat{\theta}$. -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\bm{x} = (x_1,x_2,\cdots,X_n)$. -Let $\bm{x}_i$ denote the vector -\[ -\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -\] - -which equals the vector $\bm{x}$ with the exception that observation -number $i$ is left out. Using this notation, define -$\widehat{\theta}_i$ to be the estimator -$\widehat{\theta}$ computed using $\vec{X}_i$. - - -% !split -\subsection*{Jackknife code example} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from numpy import * -from numpy.random import randint, randn -from time import time - -def jackknife(data, stat): - n = len(data);t = zeros(n); inds = arange(n); t0 = time() - ## 'jackknifing' by leaving out an observation for each i - for i in range(n): - t[i] = stat(delete(data,i) ) - - # analysis - print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :") - print("original bias std. error") - print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5)) - - return t - - -# Returns mean of data samples -def stat(data): - return mean(data) - - -mu, sigma = 100, 15 -datapoints = 10000 -x = mu + sigma*random.randn(datapoints) -# jackknife returns the data sample -t = jackknife(x, stat) - -\end{minted} - - -% !split -\subsection*{Resampling methods: Bootstrap} - -% --- begin paragraph admon --- -\paragraph{} -Bootstrapping is a nonparametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: -\begin{enumerate} -\item The bootstrap is quite general, although there are some cases in which it fails. - -\item Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. - -\item It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. - -\item It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples). -\end{enumerate} - -\noindent -% --- end paragraph admon --- - - - - -% !split -\subsection*{Resampling methods: Bootstrap background} - -Since $\widehat{\theta} = \widehat{\theta}(\bm{X})$ is a function of random variables, -$\widehat{\theta}$ itself must be a random variable. Thus it has -a pdf, call this function $p(\bm{t})$. The aim of the bootstrap is to -estimate $p(\bm{t})$ by the relative frequency of -$\widehat{\theta}$. You can think of this as using a histogram -in the place of $p(\bm{t})$. If the relative frequency closely -resembles $p(\vec{t})$, then using numerics, it is straight forward to -estimate all the interesting parameters of $p(\bm{t})$ using point -estimators. - - -% !split -\subsection*{Resampling methods: More Bootstrap background} - -In the case that $\widehat{\theta}$ has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of $X_i$, $p(x)$, had been known, then it would have -been straight forward to do this by: -\begin{enumerate} -\item Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \cdots, X_n^*)$. - -\item Then using these numbers, we could compute a replica of $\widehat{\theta}$ called $\widehat{\theta}^*$. -\end{enumerate} - -\noindent -By repeated use of (1) and (2), many -estimates of $\widehat{\theta}$ could have been obtained. The -idea is to use the relative frequency of $\widehat{\theta}^*$ -(think of a histogram) as an estimate of $p(\bm{t})$. - -% !split -\subsection*{Resampling methods: Bootstrap approach} - -But -unless there is enough information available about the process that -generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general -unknown. Therefore, \href{{https://projecteuclid.org/euclid.aos/1176344552}}{Efron in 1979} asked the -question: What if we replace $p(x)$ by the relative frequency -of the observation $X_i$; if we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - - -Instead of generating the histogram for the relative -frequency of the observation $X_i$, just draw the values -$(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector -$\bm{X}$. - -% !split -\subsection*{Resampling methods: Bootstrap steps} - -The independent bootstrap works like this: - -\begin{enumerate} -\item Draw with replacement $n$ numbers for the observed variables $\bm{x} = (x_1,x_2,\cdots,x_n)$. - -\item Define a vector $\bm{x}^*$ containing the values which were drawn from $\bm{x}$. - -\item Using the vector $\bm{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\bm{x}^*$. - -\item Repeat this process $k$ times. -\end{enumerate} - -\noindent -When you are done, you can draw a histogram of the relative frequency -of $\widehat \theta^*$. This is your estimate of the probability -distribution $p(t)$. Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of $\widehat{\theta}^*$. Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of $\widehat -\theta$, apply the etsimator $\widehat \sigma^2$ to the values -$\widehat \theta ^*$. - - -% !split -\subsection*{Code example for the Bootstrap method} - -The following code starts with a Gaussian distribution with mean value -$\mu =100$ and variance $\sigma=15$. We use this to generate the data -used in the bootstrap analysis. The bootstrap analysis returns a data -set after a given number of bootstrap operations (as many as we have -data points). This data set consists of estimated mean values for each -bootstrap operation. The histogram generated by the bootstrap method -shows that the distribution for these mean values is also a Gaussian, -centered around the mean value $\mu=100$ but with standard deviation -$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in -this case the same as the number of original data points). The value -of the standard deviation is what we expect from the central limit -theorem. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from numpy import * -from numpy.random import randint, randn -from time import time -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt - -# Returns mean of bootstrap samples -def stat(data): - return mean(data) - -# Bootstrap algorithm -def bootstrap(data, statistic, R): - t = zeros(R); n = len(data); inds = arange(n); t0 = time() - # non-parametric bootstrap - for i in range(R): - t[i] = statistic(data[randint(0,n,n)]) - - # analysis - print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") - print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) - return t - - -mu, sigma = 100, 15 -datapoints = 10000 -x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample -t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data -n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) - -# add a 'best fit' line -y = mlab.normpdf( binsboot, mean(t), std(t)) -lt = plt.plot(binsboot, y, 'r--', linewidth=1) -plt.xlabel('Smarts') -plt.ylabel('Probability') -plt.axis([99.5, 100.6, 0, 3.0]) -plt.grid(True) - -plt.show() - -\end{minted} - - -% !split -\subsection*{Code Example for Cross-validation and $k$-fold Cross-validation} - -The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import matplotlib.pyplot as plt -from sklearn.model_selection import KFold -from sklearn.linear_model import Ridge -from sklearn.model_selection import cross_val_score -from sklearn.preprocessing import PolynomialFeatures - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(3155) - -# Generate the data. -nsamples = 100 -x = np.random.randn(nsamples) -y = 3*x**2 + np.random.randn(nsamples) - -## Cross-validation on Ridge regression using KFold only - -# Decide degree on polynomial to fit -poly = PolynomialFeatures(degree = 6) - -# Decide which values of lambda to use -nlambdas = 500 -lambdas = np.logspace(-3, 5, nlambdas) - -# Initialize a KFold instance -k = 5 -kfold = KFold(n_splits = k) - -# Perform the cross-validation to estimate MSE -scores_KFold = np.zeros((nlambdas, k)) - -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - j = 0 - for train_inds, test_inds in kfold.split(x): - xtrain = x[train_inds] - ytrain = y[train_inds] - - xtest = x[test_inds] - ytest = y[test_inds] - - Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) - ridge.fit(Xtrain, ytrain[:, np.newaxis]) - - Xtest = poly.fit_transform(xtest[:, np.newaxis]) - ypred = ridge.predict(Xtest) - - scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) - - j += 1 - i += 1 - - -estimated_mse_KFold = np.mean(scores_KFold, axis = 1) - -## Cross-validation using cross_val_score from sklearn along with KFold - -# kfold is an instance initialized above as: -# kfold = KFold(n_splits = k) - -estimated_mse_sklearn = np.zeros(nlambdas) -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - - X = poly.fit_transform(x[:, np.newaxis]) - estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) - - # cross_val_score return an array containing the estimated negative mse for every fold. - # we have to the the mean of every array in order to get an estimate of the mse of the model - estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) - - i += 1 - -## Plot and compare the slightly different ways to perform cross-validation - -plt.figure() - -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') - -plt.xlabel('log10(lambda)') -plt.ylabel('mse') - -plt.legend() - -plt.show() - -\end{minted} - - -% !split -\subsection*{The bias-variance tradeoff} - - -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset $\mathcal{L}$ consisting of the data -$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$. - -Let us assume that the true data is generated from a noisy model - -\[ -\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon} -\] - -where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$. - -In our derivation of the ordinary least squares method we defined then -an approximation to the function $f$ in terms of the parameters -$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model, -that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$. - -Thereafter we found the parameters $\bm{\beta}$ by optimizing the means squared error via the so-called cost function -\[ -C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]. -\] - -We can rewrite this as -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\sigma^2. -\] - -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error $\bm{\epsilon}$. - -To derive this equation, we need to recall that the variance of $\bm{y}$ and $\bm{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\bm{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\bm{\tilde{y}}$. -We use a more compact notation in terms of the expectation value -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}})^2\right], -\] -and adding and subtracting $\mathbb{E}\left[\bm{\tilde{y}}\right]$ we get -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}}+\mathbb{E}\left[\bm{\tilde{y}}\right]-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right], -\] -which, using the abovementioned expectation values can be rewritten as -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\bm{\tilde{y}}\right]+\sigma^2, -\] -that is the rewriting in terms of the so-called bias, the variance of the model $\bm{\tilde{y}}$ and the variance of $\bm{\epsilon}$. - - - - - -% !split -\subsection*{Example code for Bias-Variance tradeoff} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 500 -n_boostraps = 100 -degree = 18 # A quite high value, just to show. -noise = 0.1 - -# Make data set. -x = np.linspace(-1, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) - -# Hold out some test data that is never used in training. -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -# Combine x transformation and model into one operation. -# Not neccesary, but convenient. -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - -# The following (m x n_bootstraps) matrix holds the column vectors y_pred -# for each bootstrap iteration. -y_pred = np.empty((y_test.shape[0], n_boostraps)) -for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - - # Evaluate the new model on the same test data each time. - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - -# Note: Expectations and variances taken w.r.t. different training -# data sets, hence the axis=1. Subsequent means are taken across the test data -# set in order to obtain a total value, but before this we have error/bias/variance -# calculated per data point in the test set. -# Note 2: The use of keepdims=True is important in the calculation of bias as this -# maintains the column vector form. Dropping this yields very unexpected results. -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) -print('Error:', error) -print('Bias^2:', bias) -print('Var:', variance) -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) - -plt.plot(x[::5, :], y[::5, :], label='f(x)') -plt.scatter(x_test, y_test, label='Data points') -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') -plt.legend() -plt.show() - -\end{minted} - - -% !split -\subsection*{Understanding what happens} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 40 -n_boostraps = 100 -maxdegree = 14 - - -# Make data set. -x = np.linspace(-3, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) -error = np.zeros(maxdegree) -bias = np.zeros(maxdegree) -variance = np.zeros(maxdegree) -polydegree = np.zeros(maxdegree) -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -for degree in range(maxdegree): - model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - y_pred = np.empty((y_test.shape[0], n_boostraps)) - for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) - variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) - print('Polynomial degree:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) - -plt.plot(polydegree, np.log10(error), label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') -plt.legend() -plt.show() - - - - -\end{minted} - -% !split -\subsection*{Summing up} - - - - -The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - - - -The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below $Var(\epsilon)$, the irreducible error. - - -What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - - -% !split -\subsection*{Another Example rom Scikit-Learn's Repository} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -""" -============================ -Underfitting vs. Overfitting -============================ - -This example demonstrates the problems of underfitting and overfitting and -how we can use linear regression with polynomial features to approximate -nonlinear functions. The plot shows the function that we want to approximate, -which is a part of the cosine function. In addition, the samples from the -real function and the approximations of different models are displayed. The -models have polynomial features of different degrees. We can see that a -linear function (polynomial with degree 1) is not sufficient to fit the -training samples. This is called **underfitting**. A polynomial of degree 4 -approximates the true function almost perfectly. However, for higher degrees -the model will **overfit** the training data, i.e. it learns the noise of the -training data. -We evaluate quantitatively **overfitting** / **underfitting** by using -cross-validation. We calculate the mean squared error (MSE) on the validation -set, the higher, the less likely the model generalizes correctly from the -training data. -""" - -print(__doc__) - -import numpy as np -import matplotlib.pyplot as plt -from sklearn.pipeline import Pipeline -from sklearn.preprocessing import PolynomialFeatures -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import cross_val_score - - -def true_fun(X): - return np.cos(1.5 * np.pi * X) - -np.random.seed(0) - -n_samples = 30 -degrees = [1, 4, 15] - -X = np.sort(np.random.rand(n_samples)) -y = true_fun(X) + np.random.randn(n_samples) * 0.1 - -plt.figure(figsize=(14, 5)) -for i in range(len(degrees)): - ax = plt.subplot(1, len(degrees), i + 1) - plt.setp(ax, xticks=(), yticks=()) - - polynomial_features = PolynomialFeatures(degree=degrees[i], - include_bias=False) - linear_regression = LinearRegression() - pipeline = Pipeline([("polynomial_features", polynomial_features), - ("linear_regression", linear_regression)]) - pipeline.fit(X[:, np.newaxis], y) - - # Evaluate the models using crossvalidation - scores = cross_val_score(pipeline, X[:, np.newaxis], y, - scoring="neg_mean_squared_error", cv=10) - - X_test = np.linspace(0, 1, 100) - plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") - plt.plot(X_test, true_fun(X_test), label="True function") - plt.scatter(X, y, edgecolor='b', s=20, label="Samples") - plt.xlabel("x") - plt.ylabel("y") - plt.xlim((0, 1)) - plt.ylim((-2, 2)) - plt.legend(loc="best") - plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( - degrees[i], -scores.mean(), scores.std())) -plt.show() -\end{minted} - - - -% !split -\subsection*{The one-dimensional Ising model} - -Let us bring back the Ising model again, but now with an additional -focus on Ridge and Lasso regression as well. We repeat some of the -basic parts of the Ising model and the setup of the training and test -data. The one-dimensional Ising model with nearest neighbor -interaction, no external field and a constant coupling constant $J$ is -given by - -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\end{align} -where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins in the system is determined by $L$. For the one-dimensional system there is no phase transition. - -We will look at a system of $L = 40$ spins with a coupling constant of $J = 1$. To get enough training data we will generate 10000 states with their respective energies. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import make_axes_locatable -import seaborn as sns -import scipy.linalg as scl -from sklearn.model_selection import train_test_split -import sklearn.linear_model as skl -import tqdm -sns.set(color_codes=True) -cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') - -L = 40 -n = int(1e4) - -spins = np.random.choice([-1, 1], size=(n, L)) -J = 1.0 - -energies = np.zeros(n) - -for i in range(n): - energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) -\end{minted} - -A more general form for the one-dimensional Ising model is - -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\end{align} - -Here we allow for interactions beyond the nearest neighbors and a more -adaptive coupling matrix. This latter expression can be formulated as -a matrix-product on the form -\begin{align} - H = X J, -\end{align} - -where $X_{jk} = s_j s_k$ and $J$ is the matrix consisting of the -elements $-J_{jk}$. This form of writing the energy fits perfectly -with the form utilized in linear regression, viz. -\begin{align} - \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}. -\end{align} -We organize the data as we did above -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X = np.zeros((n, L ** 2)) -for i in range(n): - X[i] = np.outer(spins[i], spins[i]).ravel() -y = energies -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96) - -X_train_own = np.concatenate( - (np.ones(len(X_train))[:, np.newaxis], X_train), - axis=1 -) - -X_test_own = np.concatenate( - (np.ones(len(X_test))[:, np.newaxis], X_test), - axis=1 -) -\end{minted} - -We will do all fitting with \textbf{Scikit-Learn}, - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -clf = skl.LinearRegression().fit(X_train, y_train) -\end{minted} -When extracting the $J$-matrix we make sure to remove the intercept -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -J_sk = clf.coef_.reshape(L, L) -\end{minted} -And then we plot the results -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_sk, **cmap_args) -plt.title("LinearRegression from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) -plt.show() -\end{minted} -The results perfectly with our previous discussion where we used our own code. - -% !split -\subsection*{Ridge regression} - -Having explored the ordinary least squares we move on to ridge -regression. In ridge regression we include a \textbf{regularizer}. This -involves a new cost function which leads to a new estimate for the -weights $\bm{\beta}$. This results in a penalized regression problem. The -cost function is given by - -\begin{align} - C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \bm{\beta}^T\bm{\beta}. -\end{align} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -_lambda = 0.1 -clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train) -J_ridge_sk = clf_ridge.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_ridge_sk, **cmap_args) -plt.title("Ridge from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - -plt.show() -\end{minted} - -% !split -\subsection*{LASSO regression} - -In the \textbf{Least Absolute Shrinkage and Selection Operator} (LASSO)-method we get a third cost function. - -\begin{align} - C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \sqrt{\bm{\beta}^T\bm{\beta}}. -\end{align} - -Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from \textbf{Scikit-Learn}. - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train) -J_lasso_sk = clf_lasso.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_lasso_sk, **cmap_args) -plt.title("Lasso from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - -plt.show() -\end{minted} - -It is quite striking how LASSO breaks the symmetry of the coupling -constant as opposed to ridge and OLS. We get a sparse solution with -$J_{j, j + 1} = -1$. - - - -% !split -\subsection*{Performance as function of the regularization parameter} - -We see how the different models perform for a different set of values for $\lambda$. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -lambdas = np.logspace(-4, 5, 10) - -train_errors = { - "ols_sk": np.zeros(lambdas.size), - "ridge_sk": np.zeros(lambdas.size), - "lasso_sk": np.zeros(lambdas.size) -} - -test_errors = { - "ols_sk": np.zeros(lambdas.size), - "ridge_sk": np.zeros(lambdas.size), - "lasso_sk": np.zeros(lambdas.size) -} - -plot_counter = 1 - -fig = plt.figure(figsize=(32, 54)) - -for i, _lambda in enumerate(tqdm.tqdm(lambdas)): - for key, method in zip( - ["ols_sk", "ridge_sk", "lasso_sk"], - [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)] - ): - method = method.fit(X_train, y_train) - - train_errors[key][i] = method.score(X_train, y_train) - test_errors[key][i] = method.score(X_test, y_test) - - omega = method.coef_.reshape(L, L) - - plt.subplot(10, 5, plot_counter) - plt.imshow(omega, **cmap_args) - plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda)) - plot_counter += 1 - -plt.show() -\end{minted} - -We see that LASSO reaches a good solution for low -values of $\lambda$, but will "wither" when we increase $\lambda$ too -much. Ridge is more stable over a larger range of values for -$\lambda$, but eventually also fades away. - -% !split -\subsection*{Finding the optimal value of $\lambda$} - -To determine which value of $\lambda$ is best we plot the accuracy of -the models when predicting the training and the testing set. We expect -the accuracy of the training set to be quite good, but if the accuracy -of the testing set is much lower this tells us that we might be -subject to an overfit model. The ideal scenario is an accuracy on the -testing set that is close to the accuracy of the training set. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fig = plt.figure(figsize=(20, 14)) - -colors = { - "ols_sk": "r", - "ridge_sk": "y", - "lasso_sk": "c" -} - -for key in train_errors: - plt.semilogx( - lambdas, - train_errors[key], - colors[key], - label="Train {0}".format(key), - linewidth=4.0 - ) - -for key in test_errors: - plt.semilogx( - lambdas, - test_errors[key], - colors[key] + "--", - label="Test {0}".format(key), - linewidth=4.0 - ) -plt.legend(loc="best", fontsize=18) -plt.xlabel(r"$\lambda$", fontsize=18) -plt.ylabel(r"$R^2$", fontsize=18) -plt.tick_params(labelsize=18) -plt.show() -\end{minted} - -From the above figure we can see that LASSO with $\lambda = 10^{-2}$ -achieves a very good accuracy on the test set. This by far surpasses the -other models for all values of $\lambda$. - - - -% !split -\subsection*{Further Exercises} - -\paragraph{Exercise 1.} -We will 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). -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -x = np.random.rand(100,1) -y = 5*x*x+0.1*np.random.randn(100,1) -\end{minted} - -\begin{enumerate} -\item Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial. - -\item Use thereafter \textbf{scikit-learn} (see again the examples in the regression slides) and compare with your own code. - -\item Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as -\end{enumerate} - -\noindent -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] - -You can use the functionality included in scikit-learn. If you feel -for it, you can use your own program and define functions which -compute the above two functions. Discuss the meaning of these -results. Try also to vary the coefficient in front of the added -stochastic noise term and discuss the quality of the fits. - - - - -\paragraph{Exercise 2, variance of the parameters $\beta$ in linear regression.} -Show that the variance of the parameters $\beta$ in the linear regression method (chapter 3, equation (3.8) of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}) is given as - -\[ -\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, -\] -with -\[ -\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, -\] -where we have assumed that we fit a function of degree $p-1$ (for example a polynomial in $x$). - - - -\paragraph{Exercise 3.} -This exercise is a continuation of exercise 1. 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. You can use the code under the Regression as an example on how to use the Ridge and the Lasso 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). -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -x = np.random.rand(100,1) -y = 5*x*x+0.1*np.random.randn(100,1) -\end{minted} - -\begin{enumerate} -\item Write your own code for the Ridge method and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 1. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. - -\item Repeat the above but using the functionality of \textbf{scikit-learn}. Compare your code with the results from \textbf{scikit-learn}. Remember to run with the same random numbers for generating $x$ and $y$. - -\item Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parametrizing 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 that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$) or use the functionality of \textbf{scikit-learn} and compute their variances. Discuss the results of these variances as functions - -\item Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results. - -\item Try to implement the cross-validation as well. - -\item Finally, using \textbf{scikit-learn} or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as -\end{enumerate} - -\noindent -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] -Discuss these quantities as functions of the variable $\lambda$ in the Ridge and Lasso regression methods. - -\paragraph{Exercise 4.} -We will study how -to fit polynomials to a specific two-dimensional function called -\href{{http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf}}{Franke's -function}. This -is a function which has been widely used when testing various interpolation and fitting -algorithms. Furthermore, after having established the model and the -method, we will employ resamling techniques such as the cross-validation and/or -the bootstrap methods, in order to perform a proper assessment of our models. - - -The Franke function, which is a weighted sum of four exponentials reads as follows -\begin{align*} -f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ -&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. -\end{align*} - -The function will be defined for $x,y\in [0,1]$. Our first step will -be to perform an OLS regression analysis of this function, trying out -a polynomial fit with an $x$ and $y$ dependence of the form $[x, y, -x^2, y^2, xy, \dots]$. We will also include cross-validation and -bootstrap as resampling techniques. As in homeworks 1 and 2, we -can use a uniform distribution to set up the arrays of values for $x$ -and $y$, or as in the example below just a fix values for $x$ and $y$ with a given step size. -In this case we will have two predictors and need to fit a -function (for example a polynomial) of $x$ and $y$. Thereafter we will -repeat much of the same procedure using the the Ridge and -Lasso regression methods, introducing thus a dependence on the bias -(penalty) $\lambda$. - - -The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from mpl_toolkits.mplot3d import Axes3D -import matplotlib.pyplot as plt -from matplotlib import cm -from matplotlib.ticker import LinearLocator, FormatStrFormatter -import numpy as np -from random import random, seed - -fig = plt.figure() -ax = fig.gca(projection='3d') - -# Make data. -x = np.arange(0, 1, 0.05) -y = np.arange(0, 1, 0.05) -x, y = np.meshgrid(x,y) - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -z = FrankeFunction(x, y) - -# Plot the surface. -surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm, - linewidth=0, antialiased=False) - -# Customize the z axis. -ax.set_zlim(-0.10, 1.40) -ax.zaxis.set_major_locator(LinearLocator(10)) -ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) - -# Add a color bar which maps values to colors. -fig.colorbar(surf, shrink=0.5, aspect=5) - -plt.show() - -\end{minted} - - -We will thus again generate our own dataset for a function $\mathrm{FrankeFunction}(x,y)$ where -$x,y \in [0,1]$ could be defined by random numbers computed with the uniform -distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition -an added stochastic noise to this function using the normal distribution $\cal{N}(0,1)$. - -Write your own code (using either a matrix inversion or a singular value decomposition from e.g., \textbf{numpy} ) or use your code from exercises 1 and 3 -and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\beta$ by computing their variances, evaluate the Mean Squared error (MSE) -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] - -Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm -and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models. - - -Write then your own code for the Ridge method, either using matrix -inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the -previous exercise (for the same polynomials and include resampling -techniques) but now for different values of $\lambda$. Compare and -analyze your results with those obtained with standard OLS. Study the -dependence on $\lambda$ while also varying eventually the strength of -the noise in your expression for $\mathrm{FrankeFunction}(x,y)$. - -Then perform the same studies but now with Lasso regression. Use the functionalities of -\textbf{scikit-learn}. Give a critical discussion of the three methods and a -judgement of which model fits the data best. - - -% ------------------- end of main content --------------- - -\end{document} - diff --git a/doc/src/Regression/Regression.tex.old~~ b/doc/src/Regression/Regression.tex.old~~ deleted file mode 100644 index 53761ed23..000000000 --- a/doc/src/Regression/Regression.tex.old~~ +++ /dev/null @@ -1,3673 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% - - -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{fancyvrb} % packages needed for verbatim environments -\usepackage{minted} -\usemintedstyle{default} - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -\usepackage[framemethod=TikZ]{mdframed} - -% --- begin definitions of admonition environments --- - -% --- end of definitions of admonition environments --- - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Jul 22, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection{Why Linear Regression (aka Ordinary Least Squares and family)} - -Fitting a continuous function with linear parameterization in terms of the parameters $\bm{\beta}$. -\begin{itemize} -\item Method of choice for fitting a continuous function! - -\item Gives an excellent introduction to central Machine Learning features with \textbf{understandable pedagogical} links to other methods like \textbf{Neural Networks}, \textbf{Support Vector Machines} etc - -\item Analytical expression for the fitting parameters $\bm{\beta}$ - -\item Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more - -\item Analytical relation with probabilistic interpretations - -\item Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics - -\item Easy to code! And links well with classification problems and logistic regression and neural networks - -\item Allows for \textbf{easy} hands-on understanding of gradient descent methods - -\item and many more features -\end{itemize} - -\noindent -For more discussions of Ridge and Lasso regression, \href{{https://arxiv.org/abs/1509.09169}}{Wessel van Wieringen's} article is highly recommended. -Similarly, \href{{https://arxiv.org/abs/1803.08823}}{Mehta et al's article} is also recommended. - - -% !split -\subsection{Regression analysis, overarching aims} - -% --- begin paragraph admon --- -\paragraph{} - -Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\bm{x} =[x_0, x_1,\dots, x_{n-1}]^T$. -The first variable is called the \textbf{dependent}, the \textbf{outcome} or the \textbf{response} variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable. - -A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$, that is the conditional distribution for $\bm{y}$ with a given $\bm{x}$. The estimation of $p(\bm{y}\vert \bm{x})$ is made using a data set with -\begin{itemize} -\item $n$ cases $i = 0, 1, 2, \dots, n-1$ - -\item Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ - -\item $p$ so-called explanatory (independent or predictor) variables $\bm{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}]$ with $i = 0, 1, 2, \dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. -\end{itemize} - -\noindent - The goal of the regression analysis is to extract/exploit relationship between $\bm{y}$ and $\bm{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. -% --- end paragraph admon --- - - - -% !split -\subsection{Regression analysis, overarching aims II} - -% --- begin paragraph admon --- -\paragraph{} - - -Consider an experiment in which $p$ characteristics of $n$ samples are -measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix -$\mathbf{X}$. - -The matrix $\mathbf{X}$ is called the \emph{design -matrix}. Additional information of the samples is available in the -form of $\bm{y}$ (also as above). The variable $\bm{y}$ is -generally referred to as the \emph{response variable}. The aim of -regression analysis is to explain $\bm{y}$ in terms of -$\bm{X}$ through a functional relationship like $y_i = -f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of -$f(\cdot)$ is available, it is common to assume a linear relationship -between $\bm{X}$ and $\bm{y}$. This assumption gives rise to -the \emph{linear regression model} where $\bm{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T}$ are the \emph{regression parameters}. - -Linear regression gives us a set of analytical equations for the parameters $\beta_j$. -% --- end paragraph admon --- - - - - - -% !split -\subsection{Examples} - -% --- begin paragraph admon --- -\paragraph{} -In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$, -consider the model we discussed for describing nuclear binding energies. - -There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. -Assuming -\[ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, -\] -we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms. -This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a -$p\times n$ matrix $\bm{X}$. - -Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called \href{{https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub}}{credit card default data from Taiwan}. The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \times 30000$ -% --- end paragraph admon --- - - - - - - - -% !split -\subsection{General linear models} - -% --- begin paragraph admon --- -\paragraph{} -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\bm{y}=[y_0,y_1,\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\bm{x}=[x_0,x_1,\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. - -Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is -\[ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, -\] -where $\epsilon_i$ is the error in our approximation. -% --- end paragraph admon --- - - - - -% !split -\subsection{Rewriting the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} -For every set of values $y_i,x_i$ we have thus the corresponding set of equations -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -% --- end paragraph admon --- - - - - -% !split -\subsection{Rewriting the fitting procedure as a linear algebra problem, more details} - -% --- begin paragraph admon --- -\paragraph{} -Defining the vectors -\[ -\bm{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -\] -and -\[ -\bm{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -\] -and -\[ -\bm{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -\] -and the design matrix -\[ -\bm{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -\] -we can rewrite our equations as -\[ -\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. -\] -The above design matrix is called a \href{{https://en.wikipedia.org/wiki/Vandermonde_matrix}}{Vandermonde matrix}. -% --- end paragraph admon --- - - - - -% !split -\subsection{Generalizing the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} - -We are obviously not limited to the above polynomial expansions. We -could replace the various powers of $x$ with elements of Fourier -series or instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j -x_i)}$, or time series or other orthogonal functions. For every set -of values $y_i,x_i$ we can then generalize the equations to - -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} - -\textbf{Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!} -% --- end paragraph admon --- - - - - -% !split -\subsection{Generalizing the fitting procedure as a linear algebra problem} - -% --- begin paragraph admon --- -\paragraph{} -We redefine in turn the matrix $\bm{X}$ as -\[ -\bm{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -\] -and without loss of generality we rewrite again our equations as -\[ -\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. -\] -The left-hand side of this equation is kwown. Our error vector $\bm{\epsilon}$ and the parameter vector $\bm{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? -% --- end paragraph admon --- - - - - -% !split -\subsection{Optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -We have defined the matrix $\bm{X}$ via the equations -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} - -As we noted above, we stayed with a system with the design matrix - $\bm{X}\in {\mathbb{R}}^{n\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define -our matrix as $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements. -% --- end paragraph admon --- - - - - -% !split -\subsection{Our model for the nuclear binding energies} - -In our \href{{https://compphysics.github.io/MachineLearningMSU/doc/pub/Introduction/html/Introduction.html}}{introductory notes} we looked at the so-called \href{{https://en.wikipedia.org/wiki/Semi-empirical_mass_formula}}{liguid drop model}. Let us remind ourselves about what we did by looking at the code. - -We restate the parts of the code we are most interested in. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from IPython.display import display -import os - -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("MassEval2016.dat"),'r') - - -# Read the experimental data with Pandas -Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), - names=('N', 'Z', 'A', 'Element', 'Ebinding'), - widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), - header=39, - index_col=False) - -# Extrapolated values are indicated by '#' in place of the decimal place, so -# the Ebinding column won't be numeric. Coerce to float and drop these entries. -Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') -Masses = Masses.dropna() -# Convert from keV to MeV. -Masses['Ebinding'] /= 1000 - -# Group the DataFrame by nucleon number, A. -Masses = Masses.groupby('A') -# Find the rows of the grouped DataFrame with the maximum binding energy. -Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) -A = Masses['A'] -Z = Masses['Z'] -N = Masses['N'] -Element = Masses['Element'] -Energies = Masses['Ebinding'] - -# Now we set up the design matrix X -X = np.zeros((len(A),5)) -X[:,0] = 1 -X[:,1] = A -X[:,2] = A**(2.0/3.0) -X[:,3] = A**(-1.0/3.0) -X[:,4] = A**(-1.0) -# Then nice printout using pandas -DesignMatrix = pd.DataFrame(X) -DesignMatrix.index = A -DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A'] -display(DesignMatrix) -\end{minted} - -With $\bm{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as -\[ -\bm{\tilde{y}}= \bm{X}\bm{\beta}, -\] -throughout these lectures. - - -% !split -\subsection{Optimizing our parameters, more details} - -% --- begin paragraph admon --- -\paragraph{} -With the above we use the design matrix to define the approximation $\bm{\tilde{y}}$ via the unknown quantity $\bm{\beta}$ as -\[ -\bm{\tilde{y}}= \bm{X}\bm{\beta}, -\] -and in order to find the optimal parameters $\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parameterized values $\tilde{y}_i$, namely -\[ -C(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, -\] -or using the matrix $\bm{X}$ and in a more compact matrix-vector notation as -\[ -C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}^T\bm{\beta}\right)^T\left(\bm{y}-\bm{X}^T\bm{\beta}\right)\right\}. -\] -This function is one possible way to define the so-called cost function. - - - -It is also common to define -the function $Q$ as - -\[ -C(\bm{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, -\] -since when taking the first derivative with respect to the unknown parameters $\beta$, the factor of $2$ cancels out. -% --- end paragraph admon --- - - - - -% !split -\subsection{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} - -The function -\[ -C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}, -\] -can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. -When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises) -\[ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -\] - -where $\langle y_i \rangle$ is the mean value. Keep in mind also that -till now we have treated $y_i$ as the exact value. Normally, the -response (dependent or outcome) variable $y_i$ the outcome of a -numerical experiment or another type of experiment and is thus only an -approximation to the true value. It is then always accompanied by an -error estimate, often limited to a statistical error estimate given by -the standard deviation discussed earlier. In the discussion here we -will treat $y_i$ as our exact value for the response variable. - -In order to find the parameters $\beta_i$ we will then minimize the spread of $C(\bm{\beta})$, that is we are going to solve the problem -\[ -{\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\}. -\] -In practical terms it means we will require -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -\] -which results in -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -\] -or in a matrix-vector form as -\[ -\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right). -\] -% --- end paragraph admon --- - - - - -% !split -\subsection{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -We can rewrite -\[ -\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right), -\] -as -\[ -\bm{X}^T\bm{y} = \bm{X}^T\bm{X}\bm{\beta}, -\] -and if the matrix $\bm{X}^T\bm{X}$ is invertible we have the solution -\[ -\bm{\beta} =\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] - -We note also that since our design matrix is defined as $\bm{X}\in -{\mathbb{R}}^{n\times p}$, the product $\bm{X}^T\bm{X} \in -{\mathbb{R}}^{p\times p}$. In the above case we have that $p \ll n$, -in our case $p=5$ meaning that we end up with inverting a small -$5\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional -matrices to invert. The methods discussed here and for many other -supervised learning algorithms like classification with logistic -regression or support vector machines, exhibit dimensionalities which -allow for the usage of direct linear algebra methods such as \textbf{LU} decomposition or \textbf{Singular Value Decomposition} (SVD) for finding the inverse of the matrix -$\bm{X}^T\bm{X}$. -% --- end paragraph admon --- - - - -% !split -\subsection{Interpretations and optimizing our parameters} - -% --- begin paragraph admon --- -\paragraph{} -The residuals $\bm{\epsilon}$ are in turn given by -\[ -\bm{\epsilon} = \bm{y}-\bm{\tilde{y}} = \bm{y}-\bm{X}\bm{\beta}, -\] -and with -\[ -\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, -\] -we have -\[ -\bm{X}^T\bm{\epsilon}=\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, -\] -meaning that the solution for $\bm{\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. -% --- end paragraph admon --- - - - - -Let us now return to our nuclear binding energies and simply code the above equations. - -% !split -\subsection{Own code for Ordinary Least Squares} - -It is rather straightforward to implement the matrix inversion and obtain the parameters $\bm{\beta}$. After having defined the matrix $\bm{X}$ we simply need to -write -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# matrix inversion to find beta -beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies) -# and then make the prediction -ytilde = X @ beta -\end{minted} -Alternatively, you can use the least squares functionality in \textbf{Numpy} as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fit = np.linalg.lstsq(X, Energies, rcond =None)[0] -ytildenp = np.dot(fit,X.T) -\end{minted} - -And finally we plot our fit with and compare with data -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -Masses['Eapprox'] = ytilde -# Generate a plot comparing the experimental with the fitted values values. -fig, ax = plt.subplots() -ax.set_xlabel(r'$A = N + Z$') -ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') -ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, - label='Ame2016') -ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', - label='Fit') -ax.legend() -save_fig("Masses2016OLS") -plt.show() -\end{minted} - -% !split -\subsection{Adding error analysis and training set up} - -We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. -Since we are not using _Scikit-Learn here we can define our own $R2$ function as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) -\end{minted} -and we would be using it as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -print(R2(Energies,ytilde)) -\end{minted} - -We can easily add our \textbf{MSE} score as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -print(MSE(Energies,ytilde)) -\end{minted} -and finally the relative error as -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def RelativeError(y_data,y_model): - return abs((y_data-y_model)/y_data) -print(RelativeError(Energies, ytilde)) -\end{minted} - - - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -Normally, the response (dependent or outcome) variable $y_i$ is the -outcome of a numerical experiment or another type of experiment and is -thus only an approximation to the true value. It is then always -accompanied by an error estimate, often limited to a statistical error -estimate given by the standard deviation discussed earlier. In the -discussion here we will treat $y_i$ as our exact value for the -response variable. - -Introducing the standard deviation $\sigma_i$ for each measurement -$y_i$, we define now the $\chi^2$ function (omitting the $1/n$ term) -as - -\[ -\chi^2(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\frac{1}{\bm{\Sigma^2}}\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, -\] -where the matrix $\bm{\Sigma}$ is a diagonal matrix with $\sigma_i$ as matrix elements. -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -In order to find the parameters $\beta_i$ we will then minimize the spread of $\chi^2(\bm{\beta})$ by requiring -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -\] -which results in -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -\] -or in a matrix-vector form as -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right). -\] -where we have defined the matrix $\bm{A} =\bm{X}/\bm{\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\sigma_i$ and the vector $\bm{b}$ with elements $b_i = y_i/\sigma_i$. -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -We can rewrite -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right), -\] -as -\[ -\bm{A}^T\bm{b} = \bm{A}^T\bm{A}\bm{\beta}, -\] -and if the matrix $\bm{A}^T\bm{A}$ is invertible we have the solution -\[ -\bm{\beta} =\left(\bm{A}^T\bm{A}\right)^{-1}\bm{A}^T\bm{b}. -\] -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -If we then introduce the matrix -\[ -\bm{H} = \left(\bm{A}^T\bm{A}\right)^{-1}, -\] -we have then the following expression for the parameters $\beta_j$ (the matrix elements of $\bm{H}$ are $h_{ij}$) -\[ -\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} -\] -We state without proof the expression for the uncertainty in the parameters $\beta_j$ as (we leave this as an exercise) -\[ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -\] -resulting in -\[ -\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! -\] -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} -The first step here is to approximate the function $y$ with a first-order polynomial, that is we write -\[ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -\] -By computing the derivatives of $\chi^2$ with respect to $\beta_0$ and $\beta_1$ show that these are given by -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -\] -and -\[ -\frac{\partial \chi^2(\bm{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -\] -% --- end paragraph admon --- - - - -% !split -\subsection{The $\chi^2$ function} - -% --- begin paragraph admon --- -\paragraph{} - -For a linear fit (a first-order polynomial) we don't need to invert a matrix!! -Defining -\[ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -\] - -\[ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -\] - -\[ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -\] - -\[ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -\] - -\[ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -\] - -we obtain - -\[ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -\] - -\[ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -\] - -This approach (different linear and non-linear regression) suffers -often from both being underdetermined and overdetermined in the -unknown coefficients $\beta_i$. A better approach is to use the -Singular Value Decomposition (SVD) method discussed below. Or using -Lasso and Ridge regression. See below. -% --- end paragraph admon --- - - - - -% !split -\subsection{Fitting an Equation of State for Dense Nuclear Matter} - -Before we continue, let us introduce yet another example. We are going to fit the -nuclear equation of state using results from many-body calculations. -The equation of state we have made available here, as function of -density, has been derived using modern nucleon-nucleon potentials with -\href{{https://www.sciencedirect.com/science/article/pii/S0370157399001106}}{the addition of three-body -forces}. This -time the file is presented as a standard \textbf{csv} file. - -The beginning of the Python code here is similar to what you have seen before, -with the same initializations and declarations. We use also \textbf{pandas} -again, rather extensively in order to organize our data. - -The difference now is that we use \textbf{Scikit-Learn's} regression tools -instead of our own matrix inversion implementation. Furthermore, we -sneak in \textbf{Ridge} regression (to be discussed below) which includes a -hyperparameter $\lambda$, also to be explained below. - -% !split -\subsection{The code} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import matplotlib.pyplot as plt -import sklearn.linear_model as skl -from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error - -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organize the data into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops -X = np.zeros((len(Density),4)) -X[:,3] = Density**(4.0/3.0) -X[:,2] = Density -X[:,1] = Density**(2.0/3.0) -X[:,0] = 1 - -# We use now Scikit-Learn's linear regressor and ridge regressor -# OLS part -clf = skl.LinearRegression().fit(X, Energies) -ytilde = clf.predict(X) -EoS['Eols'] = ytilde -# The mean squared error -print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(Energies, ytilde)) -# Mean absolute error -print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde)) -print(clf.coef_, clf.intercept_) - -# The Ridge regression with a hyperparameter lambda = 0.1 -_lambda = 0.1 -clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies) -yridge = clf_ridge.predict(X) -EoS['Eridge'] = yridge -# The mean squared error -print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(Energies, yridge)) -# Mean absolute error -print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge)) -print(clf_ridge.coef_, clf_ridge.intercept_) - -fig, ax = plt.subplots() -ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$') -ax.set_ylabel(r'Energy per particle') -ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2, - label='Theoretical data') -ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m', - label='OLS') -ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g', - label='Ridge $\lambda = 0.1$') -ax.legend() -save_fig("EoSfitting") -plt.show() -\end{minted} - -The above simple polynomial in density $\rho$ gives an excellent fit -to the data. Can you give an interpretation of the various powers of $\rho$? - -We note also that there is a small deviation between the -standard OLS and the Ridge regression at higher densities. We discuss this in more detail -below. - - -% !split -\subsection{Splitting our Data in Training and Test data} - -It is normal in essentially all Machine Learning studies to split the -data in a training set and a test set (sometimes also an additional -validation set). \textbf{Scikit-Learn} has an own function for this. There -is no explicit recipe for how much data should be included as training -data and say test data. An accepted rule of thumb is to use -approximately $2/3$ to $4/5$ of the data as training data. We will -postpone a discussion of this splitting to the end of these notes and -our discussion of the so-called \textbf{bias-variance} tradeoff. Here we -limit ourselves to repeat the above equation of state fitting example -but now splitting the data into a training set and a test set. - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organized into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops -X = np.zeros((len(Density),5)) -X[:,0] = 1 -X[:,1] = Density**(2.0/3.0) -X[:,2] = Density -X[:,3] = Density**(4.0/3.0) -X[:,4] = Density**(5.0/3.0) -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) -# matrix inversion to find beta -beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train) -# and then make the prediction -ytilde = X_train @ beta -print("Training R2") -print(R2(y_train,ytilde)) -print("Training MSE") -print(MSE(y_train,ytilde)) -ypredict = X_test @ beta -print("Test R2") -print(R2(y_test,ypredict)) -print("Test MSE") -print(MSE(y_test,ypredict)) -\end{minted} - - -% !split -\subsection{The singular value decomposition} - - -% --- begin paragraph admon --- -\paragraph{} - -The examples we have looked at so far are cases where we normally can -invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion as we -did both for the masses and the fitting of the equation of state, -leads to row vectors of the design matrix which are essentially -orthogonal due to the polynomial character of our model. This may -however not the be case in general and a standard matrix inversion -algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit -the coupling constant of the widely used Ising model. -There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. - -This is given by the \textbf{Singular Value Decomposition} algorithm, perhaps -the most powerful linear algebra algorithm. Let us look at a -different example where we may have problems with the standard matrix -inversion algorithm. Thereafter we dive into the math of the SVD. -% --- end paragraph admon --- - - - -% !split -\subsection{The Ising model} - -The one-dimensional Ising model with nearest neighbor interaction, no -external field and a constant coupling constant $J$ is given by - -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\end{align} - -where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins -in the system is determined by $L$. For the one-dimensional system -there is no phase transition. - -We will look at a system of $L = 40$ spins with a coupling constant of -$J = 1$. To get enough training data we will generate 10000 states -with their respective energies. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import make_axes_locatable -import seaborn as sns -import scipy.linalg as scl -from sklearn.model_selection import train_test_split -import tqdm -sns.set(color_codes=True) -cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') - -L = 40 -n = int(1e4) - -spins = np.random.choice([-1, 1], size=(n, L)) -J = 1.0 - -energies = np.zeros(n) - -for i in range(n): - energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) -\end{minted} - -Here we use ordinary least squares -regression to predict the energy for the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use linear regression to fit a value for -the coupling constant to achieve this. - -% !split -\subsection{Reformulating the problem to suit regression} - -A more general form for the one-dimensional Ising model is - -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\end{align} - -Here we allow for interactions beyond the nearest neighbors and a state dependent -coupling constant. This latter expression can be formulated as -a matrix-product -\begin{align} - \bm{H} = \bm{X} J, -\end{align} - -where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the -elements $-J_{jk}$. This form of writing the energy fits perfectly -with the form utilized in linear regression, that is - -\begin{align} - \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}, -\end{align} - -We split the data in training and test data as discussed in the previous example - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X = np.zeros((n, L ** 2)) -for i in range(n): - X[i] = np.outer(spins[i], spins[i]).ravel() -y = energies -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) -\end{minted} - -% !split -\subsection{Linear regression} - -In the ordinary least squares method we choose the cost function - -\begin{align} - C(\bm{X}, \bm{\beta})= \frac{1}{n}\left\{(\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y})\right\}. -\end{align} - -We then find the extremal point of $C$ by taking the derivative with respect to $\bm{\beta}$ as discussed above. -This yields the expression for $\bm{\beta}$ to be - -\[ - \bm{\beta} = \frac{\bm{X}^T \bm{y}}{\bm{X}^T \bm{X}}, -\] - -which immediately imposes some requirements on $\bm{X}$ as there must exist -an inverse of $\bm{X}^T \bm{X}$. If the expression we are modeling contains an -intercept, i.e., a constant term, we must make sure that the -first column of $\bm{X}$ consists of $1$. We do this here - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X_train_own = np.concatenate( - (np.ones(len(X_train))[:, np.newaxis], X_train), - axis=1 -) -X_test_own = np.concatenate( - (np.ones(len(X_test))[:, np.newaxis], X_test), - axis=1 -) -\end{minted} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray: - return scl.inv(x.T @ x) @ (x.T @ y) -beta = ols_inv(X_train_own, y_train) -\end{minted} - - -% !split -\subsection{Singular Value decomposition} - -Doing the inversion directly turns out to be a bad idea since the matrix -$\bm{X}^T\bm{X}$ is singular. An alternative approach is to use the \textbf{singular -value decomposition}. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for $\bm{\beta}$ as - -\[ - \bm{\beta} = \bm{X}^{+}\bm{y}, -\] - -where the pseudoinverse of $\bm{X}$ is given by - -\[ - \bm{X}^{+} = \frac{\bm{X}^T}{\bm{X}^T\bm{X}}. -\] - -Using singular value decomposition we can decompose the matrix $\bm{X} = \bm{U}\bm{\Sigma} \bm{V}^T$, -where $\bm{U}$ and $\bm{V}$ are orthogonal(unitary) matrices and $\bm{\Sigma}$ contains the singular values (more details below). -where $X^{+} = V\Sigma^{+} U^T$. This reduces the equation for -$\omega$ to -\begin{align} - \bm{\beta} = \bm{V}\bm{\Sigma}^{+} \bm{U}^T \bm{y}. -\end{align} - -Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as $\mathcal{O}(n^3)$, where $n$ is the number of elements in a -general matrix. Instead, doing $QR$-factorization and solving the -linear system as an equation would reduce this down to -$\mathcal{O}(n^2)$ operations. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray: - u, s, v = scl.svd(x) - return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y -\end{minted} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -beta = ols_svd(X_train_own,y_train) -\end{minted} - -When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -J = beta[1:].reshape(L, L) -\end{minted} - -A way of looking at the coefficients in $J$ is to plot the matrices as images. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J, **cmap_args) -plt.title("OLS", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) -plt.show() -\end{minted} -It is interesting to note that OLS -considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as -valid matrix elements for $J$. -In our discussion below on hyperparameters and Ridge and Lasso regression we will see that -this problem can be removed, partly and only with Lasso regression. - -In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? - - -% !split -\subsection{Linear Regression Problems} - -One of the typical problems we encounter with linear regression, in particular -when the matrix $\bm{X}$ (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of $\bm{X}$ -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} - -The columns of $\bm{X}$ are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of $\mathbf{X}$ is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. - -Super-collinearity of an $(n \times p)$-dimensional design matrix $\mathbf{X}$ implies -that the inverse of the matrix $\bm{X}^T\bm{x}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -\begin{align*} -\bm{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -We see easily that $\mbox{det}(\bm{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined. -This is equivalent to saying that the matrix $\bm{X}$ has at least an eigenvalue which is zero. - - -% !split -\subsection{Fixing the singularity} - -If our design matrix $\bm{X}$ which enters the linear regression problem -\begin{align} -\bm{\beta} & = (\bm{X}^{T} \bm{X})^{-1} \bm{X}^{T} \bm{y}, -\end{align} -has linearly dependent column vectors, we will not be able to compute the inverse -of $\bm{X}^T\bm{X}$ and we cannot find the parameters (estimators) $\beta_i$. -The estimators are only well-defined if $(\bm{X}^{T}\bm{X})^{-1}$ exits. -This is more likely to happen when the matrix $\bm{X}$ is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters $\beta_i$ cannot be estimated. - -A cheap \emph{ad hoc} approach is simply to add a small diagonal component to the matrix to invert, that is we change -\[ -\bm{X}^{T} \bm{X} \rightarrow \bm{X}^{T} \bm{X}+\lambda \bm{I}, -\] -where $\bm{I}$ is the identity matrix. When we discuss \textbf{Ridge} regression this is actually what we end up evaluating. The parameter $\lambda$ is called a hyperparameter. More about this later. - - - -% !split -\subsection{Basic math of the SVD} - - -From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is -a so-called \href{{https://en.wikipedia.org/wiki/Normal_matrix}}{normal matrix}, that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$ -we have $\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ or if $\bm{X}\in {\mathbb{C}}^{n\times n}$ we have $\bm{X}\bm{X}^{\dagger}=\bm{X}^{\dagger}\bm{X}$. -The matrix has then a set of eigenpairs - -\[ -(\lambda_1,\bm{u}_1),\dots, (\lambda_n,\bm{u}_n), -and the eigenvalues are given by the diagonal matrix -\[ -\bm{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). -\] -The matrix $\bm{X}$ can be written in terms of an orthogonal/unitary transformation $\bm{U}$ -\[ -\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T, -\] -with $\bm{U}\bm{U}^T=\bm{I}$ or $\bm{U}\bm{U}^{\dagger}=\bm{I}$. - -Not all square matrices are diagonalizable. A matrix like the one discussed above -\[ -\bm{X} = \begin{bmatrix} -1& -1 \\ -1& -1\\ -\end{bmatrix} -\] -is not diagonalizable, it is a so-called \href{{https://en.wikipedia.org/wiki/Defective_matrix}}{defective matrix}. It is easy to see that the condition -$\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ is not fulfilled. - - -% !split -\subsection{The SVD, a Fantastic Algorithm} - - -However, and this is the strength of the SVD algorithm, any general -matrix $\bm{X}$ can be decomposed in terms of a diagonal matrix and -two orthogonal/unitary matrices. The \href{{https://en.wikipedia.org/wiki/Singular_value_decomposition}}{Singular Value Decompostion -(SVD) theorem} -states that a general $m\times n$ matrix $\bm{X}$ can be written in -terms of a diagonal matrix $\bm{\Sigma}$ of dimensionality $n\times n$ -and two orthognal matrices $\bm{U}$ and $\bm{V}$, where the first has -dimensionality $m \times m$ and the last dimensionality $n\times n$. -We have then - -\[ -\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T -\] - -As an example, the above defective matrix can be decomposed as - -\[ -\bm{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T, -\] - -with eigenvalues $\sigma_1=2$ and $\sigma_2=0$. -The SVD exits always! - - -% !split -\subsection{Another Example} - -Consider the following matrix which can be SVD decomposed as - -\[ -\bm{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T. -\] - -This is a $3\times 2$ matrix which is decomposed in terms of a -$3\times 3$ matrix $\bm{U}$, and a $2\times 2$ matrix $\bm{V}$. It is easy to see -that $\bm{U}$ and $\bm{V}$ are orthogonal (how?). - -And the SVD -decomposition (singular values) gives eigenvalues -$\sigma_i\geq\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=2$, the -eigenvalues (singular values) are zero. - -In the general case, where our design matrix $\bm{X}$ has dimension -$n\times p$, the matrix is thus decomposed into an $n\times n$ -orthogonal matrix $\bm{U}$, a $p\times p$ orthogonal matrix $\bm{V}$ -and a diagonal matrix $\bm{\Sigma}$ with $r=\mathrm{min}(n,p)$ -singular values $\sigma_i\lg 0$ on the main diagonal and zeros filling -the rest of the matrix. There are at most $p$ singular values -assuming that $n > p$. In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have $p > n$. These are often cases that lead to -near singular or singular matrices. - -The columns of $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors. - -% !split -\subsection{Economy-size SVD} - -If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n -\times n$. The last $n-p$ columns of $\bm{U}$ become however -irrelevant in our calculations since they are multiplied with the -zeros in $\bm{\Sigma}$. - -The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, $\bm{\Sigma}$, along with the columns -in either $\bm{U}$ or $\bm{V}$ that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. - -If $n > p$, we keep only the first $p$ columns of $\bm{U}$ and $\bm{\Sigma}$ has dimension $p\times p$. -If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\Sigma}$ has dimension $n\times n$. -The $n=p$ case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. - -% !split -\subsection{Mathematical Properties} - -There are several interesting mathematical properties which will be -relevant when we are going to discuss the differences between say -ordinary least squares (OLS) and \textbf{Ridge} regression. - -We have from OLS that the parameters of the linear approximation are given by -\[ -\bm{\tilde{y}} = \bm{X}\bm{\beta} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] - -The matrix to invert can be rewritten in terms of our SVD decomposition as - -\[ -\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T. -\] -Using the orthogonality properties of $\bm{U}$ we have - -\[ -\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T = \bm{V}\bm{D}\bm{V}^T, -\] -with $\bm{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. - -This means that -\[ -(\bm{X}^T\bm{X})\bm{V} = \bm{V}\bm{D}, -\] -that is the eigenvectors of $(\bm{X}^T\bm{X})$ are given by the columns of the right singular matrix of $\bm{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that -\[ -(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}, -\] -that is, the eigenvectors of $(\bm{X}\bm{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. - -Going back to our OLS equation we have -\[ -\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}. -\] -We will come back to this expression when we discuss Ridge regression. - - -% !split -\subsection{Ridge and LASSO Regression} - -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_{\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\}. -\] -or we can state it as -\[ -{\displaystyle \min_{\bm{\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 \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, -\] -where we have used the definition of a norm-2 vector, that is -\[ -\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. -\] - -By minimizing the above equation with respect to the parameters -$\bm{\beta}$ we could then obtain an analytical expression for the -parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by -defining a new cost function to be optimized, that is - -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 -\] - -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. By defining - -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, -\] - -we have a new optimization equation -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\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 \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. -\] - - -% !split -\subsection{More on Ridge Regression} - -Using the matrix-vector expression for Ridge regression, - -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, -\] - -by taking the derivatives with respect to $\bm{\beta}$ we obtain then -a slightly modified matrix inversion problem which for finite values -of $\lambda$ does not suffer from singularity problems. We obtain - -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, -\] - -with $\bm{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. - -We see that Ridge regression is nothing but the standard -OLS with a modified diagonal term added to $\bm{X}^T\bm{X}$. The -consequences, in particular for our discussion of the bias-variance -are rather interesting. - -Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had -\[ -(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}. -\] - -We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as -\[ -\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y} -\] - - -For Ridge regression this becomes - -\[ -\bm{X}\bm{\beta}^{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, -\] - -with the vectors $\bm{u}_j$ being the columns of $\bm{U}$. - -% !split -\subsection{Interpreting the Ridge results} - -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 $\bm{y}$ with respect to the -orthonormal basis $\bm{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}$. - -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. -Actually, calculating the variance of $\bm{X}\bm{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$. -With a parameter $\lambda$ we can thus shrink the role of specific parameters. - - -% !split -\subsection{More interpretations} - -For the sake of simplicity, let us assume that the design matrix is orthonormal, that is - -\[ -\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. -\] - -In this case the standard OLS results in -\[ -\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, -\] - -and - -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\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. - -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, \href{{https://arxiv.org/abs/1509.09169}}{Wessel van Wieringen's} article is highly recommended. -Similarly, \href{{https://arxiv.org/abs/1803.08823}}{Mehta et al's article} is also recommended. - -% !split -\subsection{Where are we going?} - -Before we proceed, we need to rethink what we have been doing. In our -eager to fit the data, we have omitted several important elements in -our regression analysis. In what follows we will -\begin{enumerate} -\item look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff - -\item introduce resampling techniques like cross-validation, bootstrapping and jackknife and more -\end{enumerate} - -\noindent -This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. - - - - - -% !split -\subsection{Resampling methods} - -% --- begin paragraph admon --- -\paragraph{} -Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. -% --- end paragraph admon --- - - - -% !split -\subsection{Resampling approaches can be computationally expensive} - -% --- begin paragraph admon --- -\paragraph{} - -Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. -% --- end paragraph admon --- - - - -% !split -\subsection{Why resampling methods ?} - -% --- begin paragraph admon --- -\paragraph{Statistical analysis.} - -\begin{itemize} -\item Our simulations can be treated as \emph{computer experiments}. This is particularly the case for Monte Carlo methods - -\item The results can be analysed with the same statistical tools as we would use analysing experimental data. - -\item As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. -\end{itemize} - -\noindent -% --- end paragraph admon --- - - - -% !split -\subsection{Statistical analysis} - -% --- begin paragraph admon --- -\paragraph{} - -\begin{itemize} -\item As in other experiments, many numerical experiments have two classes of errors: -\begin{itemize} - - \item Statistical errors - - \item Systematical errors - -\end{itemize} - -\noindent -\item Statistical errors can be estimated using standard tools from statistics - -\item Systematical errors are method specific and must be treated differently from case to case. -\end{itemize} - -\noindent -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -The \emph{probability distribution function (PDF)} is a function -$p(x)$ on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of $X$ occur: -\[ -p(x) = \mathrm{prob}(X=x) -\] -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us -the \emph{density} of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval $[a,\,b]$ is then just the integral: -\[ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx -\] -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. -% --- end paragraph admon --- - - - - -% !split -\subsection{Statistics, moments} - -% --- begin paragraph admon --- -\paragraph{} -A particularly useful class of special expectation values are the -\emph{moments}. The $n$-th moment of the PDF $p$ is defined as -follows: -\[ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx -\] -The zero-th moment $\langle 1\rangle$ is just the normalization condition of -$p$. The first moment, $\langle x\rangle$, is called the \emph{mean} of $p$ -and often denoted by the letter $\mu$: -\[ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, central moments} - -% --- begin paragraph admon --- -\paragraph{} -A special version of the moments is the set of \emph{central moments}, -the n-th central moment defined as: -\[ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -\] -The zero-th and first central moments are both trivial, equal $1$ and -$0$, respectively. But the second central moment, known as the -\emph{variance} of $p$, is of particular interest. For the stochastic -variable $X$, the variance is denoted as $\sigma^2_X$ or $\mathrm{var}(X)$: -\begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\end{align} -The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle}$ is called the \emph{standard deviation} of $p$. It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the \emph{spread} of $p$ around its mean. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, covariance} - -% --- begin paragraph admon --- -\paragraph{} -Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set $\{X_i\}$ of $n$ -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF $P(x_1,\dots,x_n)$. The \emph{covariance} of two -of the stochastic variables, $X_i$ and $X_j$, is defined as follows: -\begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\label{eq:def_covariance} -\end{align} -with -\[ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, more covariance} - -% --- begin paragraph admon --- -\paragraph{} -If we consider the above covariance as a matrix $C_{ij}=\mathrm{cov}(X_i,\,X_j)$, then the diagonal elements are just the familiar -variances, $C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i)$. It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables $X_i$ and -$X_j$, ($i\neq j$): -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle \\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\end{align} -% --- end paragraph admon --- - - - - - -% !split -\subsection{Statistics, independent variables} - -% --- begin paragraph admon --- -\paragraph{} -If $X_i$ and $X_j$ are independent, we get -$\langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle$, resulting in $\mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j)$. - -Also useful for us is the covariance of linear combinations of -stochastic variables. Let $\{X_i\}$ and $\{Y_i\}$ be two sets of -stochastic variables. Let also $\{a_i\}$ and $\{b_i\}$ be two sets of -scalars. Consider the linear combination: -\[ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j -\] -By the linearity of the expectation value -\[ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, more variance} - -% --- begin paragraph admon --- -\paragraph{} -Now, since the variance is just $\mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i)$, we get -the variance of the linear combination $U = \sum_i a_i X_i$: -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\label{eq:variance_linear_combination} -\end{equation} -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -\[ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -\] -\[ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -\] -which will become very useful in our study of the error in the mean -value of a set of measurements. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics and stochastic processes} - -% --- begin paragraph admon --- -\paragraph{} -A \emph{stochastic process} is a process that produces sequentially a -chain of values: -\[ -\{x_1, x_2,\dots\,x_k,\dots\}. -\] -We will call these -values our \emph{measurements} and the entire set as our measured -\emph{sample}. The action of measuring all the elements of a sample -we will call a stochastic \emph{experiment} since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF $p_X^{\phantom X}(x)$, where $X$ is just the formal symbol for the -stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of -trying to determine the full distribution $p$ we are often only -interested in finding the few lowest moments, like the mean -$\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$. -% --- end paragraph admon --- - - - - -% !split -\subsection{Statistics and sample variables} - -% --- begin paragraph admon --- -\paragraph{} -In practical situations a sample is always of finite size. Let that -size be $n$. The expectation value of a sample, the \emph{sample mean}, is then defined as follows: -\[ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -\] -The \emph{sample variance} is: -\[ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -\] -its square root being the \emph{standard deviation of the sample}. The -\emph{sample covariance} is: -\[ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, sample variance and covariance} - -% --- begin paragraph admon --- -\paragraph{} -Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq.~(\ref{eq:def_covariance}) is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. - -These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean $\mu_X$, variance $\mathrm{var}(X)$ -and covariance $\mathrm{cov}(X,Y)$. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, law of large numbers} - -% --- begin paragraph admon --- -\paragraph{} -The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean $\mu_X^{\phantom X}$ of the chosen PDF: -\[ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} -\] -The sample mean $\bar{x}_n$ works therefore as an estimate of the true -mean $\mu_X^{\phantom X}$. - -What we need to find out is how good an approximation $\bar{x}_n$ is to -$\mu_X^{\phantom X}$. In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the \emph{error} of the sample mean, or -just sample error, and denote it by $\mathrm{err}_X^{\phantom X}$. In -practice, we will only be able to produce an \emph{estimate} of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. -% --- end paragraph admon --- - - - - -% !split -\subsection{Statistics, more on sample error} - -% --- begin paragraph admon --- -\paragraph{} -Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements $x_i$ -can be associated with its own stochastic variable $X_i$. The -stochastic variable $\overline X_n$ for the sample mean $\bar{x}_n$ is -then just a linear combination, already familiar to us: -\[ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i -\] -All the coefficients are just equal $1/n$. The PDF of $\overline X_n$, -denoted by $p_{\overline X_n}(x)$ is the desired PDF of the sample -means. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -The probability density of obtaining a sample mean $\bar x_n$ -is the product of probabilities of obtaining arbitrary values $x_1, -x_2,\dots,x_n$ with the constraint that the mean of the set $\{x_i\}$ -is $\bar x_n$: -\[ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 -\] -And in particular we are interested in its variance $\mathrm{var}(\overline X_n)$. -% --- end paragraph admon --- - - - - - -% !split -\subsection{Statistics, central limit theorem} - -% --- begin paragraph admon --- -\paragraph{} -It is generally not possible to express $p_{\overline X_n}(x)$ in a -closed form given an arbitrary PDF $p_X^{\phantom X}$ and a number -$n$. But for the limit $n\to\infty$ it is possible to make an -approximation. The very important result is called \emph{the central limit theorem}. It tells us that as $n$ goes to infinity, -$p_{\overline X_n}(x)$ approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, $\mu_{X}^{\phantom X}$ -and $\sigma_{X}^{2}$, respectively: -\begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\label{eq:central_limit_gaussian} -\end{equation} -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, more technicalities} - -% --- begin paragraph admon --- -\paragraph{} -The desired variance -$\mathrm{var}(\overline X_n)$, i.e.~the sample error squared -$\mathrm{err}_X^2$, is given by: -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\label{eq:error_exact} -\end{equation} -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -$\mu_{X_i}^{\phantom X}$ of the stochastic variables $X_i$. To -calculate these requires that we know the true multivariate PDF of all -the $X_i$. But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the $X_i$, estimating all properties of -$X_i$ through the measurements of the sample. -% --- end paragraph admon --- - - - - -% !split -\subsection{Statistics} - -% --- begin paragraph admon --- -\paragraph{} -Our estimate of $\mu_{X_i}^{\phantom X}$ is then the sample mean $\bar x$ -itself, in accordance with the the central limit theorem: -\[ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x -\] -Using $\bar x$ in place of $\mu_{X_i}^{\phantom X}$ we can give an -\emph{estimate} of the covariance in Eq.~(\ref{eq:error_exact}) -\[ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, -\] -resulting in -\[ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) -\] -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics and sample variance} - -% --- begin paragraph admon --- -\paragraph{} -By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables $X_i$ -\[ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, -\] -which is approximated as -\begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\label{eq:var_estimate_i_think} -\end{equation} - -Now we can calculate an estimate of the error -$\mathrm{err}_X^{\phantom X}$ of the sample mean $\bar x_n$: -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\label{eq:error_estimate} -\end{align} -which is nothing but the sample covariance divided by the number of -measurements in the sample. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, uncorrelated results} - -% --- begin paragraph admon --- -\paragraph{} - -In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables $X_i$ are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: -\[ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), -\] -resulting in -\begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\label{eq:error_estimate_uncorrel} -\end{equation} -where in the second step we have used Eq.~(\ref{eq:var_estimate_i_think}). -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. -% --- end paragraph admon --- - - - -% !split -\subsection{Statistics, computations} - -% --- begin paragraph admon --- -\paragraph{} -For computational purposes one usually splits up the estimate of -$\mathrm{err}_X^2$, given by Eq.~(\ref{eq:error_estimate}), into two -parts -\[ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), -\] -which equals -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k 0$. We say then that the ridge estimator is biased. - -We can also compute the variance as - -\[ -\mbox{Var}[\bm{\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 $\bm{\beta}$ goes to zero. - -With this, we can compute the difference - -\[ -\mbox{Var}[\bm{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\bm{\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 $\bm{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. - -% !split -\subsection{Cross-validation} - -Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e.~the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. - -The setting of \textbf{original} and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the -\emph{training set}, plays the role of \textbf{original} data on which the model is -built. The second of these data sets, called the \emph{test set}, plays the -role of the \textbf{novel} data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of $\lambda$ using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. - - -% !split -\subsection{Computationally expensive} - -The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: - -\begin{itemize} -\item The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set. - -\item In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set. -\end{itemize} - -\noindent -% !split -\subsection{Various steps in cross-validation} - -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this $k$-fold cross-validation structures the data splitting. The -samples are divided into $k$ more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the $k$ subsets -involves a degree of randomness. This may be fully excluded when -choosing $k=n$. This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -% !split -\subsection{How to set up the cross-validation for Ridge and/or Lasso} - -\begin{itemize} -\item Define a range of interest for the penalty parameter. - -\item Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. - -\item Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, as -\end{itemize} - -\noindent -\begin{align*} -\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T} -\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1} -\bm{X}_{-i, \ast}^{T} \bm{y}_{-i} -\end{align*} - -\begin{itemize} -\item Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. - -\item Repeat the first three steps such that each sample plays the role of the test set once. - -\item Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the \emph{cross-validated log-likelihood}. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as -\end{itemize} - -\noindent -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} - -\begin{itemize} -\item The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions. -\end{itemize} - -\noindent -% !split -\subsection{Resampling methods: Jackknife and Bootstrap} - -Two famous -resampling methods are the \textbf{independent bootstrap} and \textbf{the jackknife}. - -The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as \textbf{the dependent bootstrap}. - -The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of $\overline{X}$ (which often is the case), then there is no -need for bootstrapping. - -% !split -\subsection{Resampling methods: Jackknife} - -The Jackknife works by making many replicas of the estimator $\widehat{\theta}$. -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\bm{x} = (x_1,x_2,\cdots,X_n)$. -Let $\bm{x}_i$ denote the vector -\[ -\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -\] - -which equals the vector $\bm{x}$ with the exception that observation -number $i$ is left out. Using this notation, define -$\widehat{\theta}_i$ to be the estimator -$\widehat{\theta}$ computed using $\vec{X}_i$. - - -% !split -\subsection{Jackknife code example} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from numpy import * -from numpy.random import randint, randn -from time import time - -def jackknife(data, stat): - n = len(data);t = zeros(n); inds = arange(n); t0 = time() - ## 'jackknifing' by leaving out an observation for each i - for i in range(n): - t[i] = stat(delete(data,i) ) - - # analysis - print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :") - print("original bias std. error") - print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5)) - - return t - - -# Returns mean of data samples -def stat(data): - return mean(data) - - -mu, sigma = 100, 15 -datapoints = 10000 -x = mu + sigma*random.randn(datapoints) -# jackknife returns the data sample -t = jackknife(x, stat) - -\end{minted} - - -% !split -\subsection{Resampling methods: Bootstrap} - -% --- begin paragraph admon --- -\paragraph{} -Bootstrapping is a nonparametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: -\begin{enumerate} -\item The bootstrap is quite general, although there are some cases in which it fails. - -\item Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. - -\item It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. - -\item It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples). -\end{enumerate} - -\noindent -% --- end paragraph admon --- - - - - -% !split -\subsection{Resampling methods: Bootstrap background} - -Since $\widehat{\theta} = \widehat{\theta}(\bm{X})$ is a function of random variables, -$\widehat{\theta}$ itself must be a random variable. Thus it has -a pdf, call this function $p(\bm{t})$. The aim of the bootstrap is to -estimate $p(\bm{t})$ by the relative frequency of -$\widehat{\theta}$. You can think of this as using a histogram -in the place of $p(\bm{t})$. If the relative frequency closely -resembles $p(\vec{t})$, then using numerics, it is straight forward to -estimate all the interesting parameters of $p(\bm{t})$ using point -estimators. - - -% !split -\subsection{Resampling methods: More Bootstrap background} - -In the case that $\widehat{\theta}$ has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of $X_i$, $p(x)$, had been known, then it would have -been straight forward to do this by: -\begin{enumerate} -\item Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \cdots, X_n^*)$. - -\item Then using these numbers, we could compute a replica of $\widehat{\theta}$ called $\widehat{\theta}^*$. -\end{enumerate} - -\noindent -By repeated use of (1) and (2), many -estimates of $\widehat{\theta}$ could have been obtained. The -idea is to use the relative frequency of $\widehat{\theta}^*$ -(think of a histogram) as an estimate of $p(\bm{t})$. - -% !split -\subsection{Resampling methods: Bootstrap approach} - -But -unless there is enough information available about the process that -generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general -unknown. Therefore, \href{{https://projecteuclid.org/euclid.aos/1176344552}}{Efron in 1979} asked the -question: What if we replace $p(x)$ by the relative frequency -of the observation $X_i$; if we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - - -Instead of generating the histogram for the relative -frequency of the observation $X_i$, just draw the values -$(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector -$\bm{X}$. - -% !split -\subsection{Resampling methods: Bootstrap steps} - -The independent bootstrap works like this: - -\begin{enumerate} -\item Draw with replacement $n$ numbers for the observed variables $\bm{x} = (x_1,x_2,\cdots,x_n)$. - -\item Define a vector $\bm{x}^*$ containing the values which were drawn from $\bm{x}$. - -\item Using the vector $\bm{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\bm{x}^*$. - -\item Repeat this process $k$ times. -\end{enumerate} - -\noindent -When you are done, you can draw a histogram of the relative frequency -of $\widehat \theta^*$. This is your estimate of the probability -distribution $p(t)$. Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of $\widehat{\theta}^*$. Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of $\widehat -\theta$, apply the etsimator $\widehat \sigma^2$ to the values -$\widehat \theta ^*$. - - -% !split -\subsection{Code example for the Bootstrap method} - -The following code starts with a Gaussian distribution with mean value -$\mu =100$ and variance $\sigma=15$. We use this to generate the data -used in the bootstrap analysis. The bootstrap analysis returns a data -set after a given number of bootstrap operations (as many as we have -data points). This data set consists of estimated mean values for each -bootstrap operation. The histogram generated by the bootstrap method -shows that the distribution for these mean values is also a Gaussian, -centered around the mean value $\mu=100$ but with standard deviation -$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in -this case the same as the number of original data points). The value -of the standard deviation is what we expect from the central limit -theorem. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from numpy import * -from numpy.random import randint, randn -from time import time -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt - -# Returns mean of bootstrap samples -def stat(data): - return mean(data) - -# Bootstrap algorithm -def bootstrap(data, statistic, R): - t = zeros(R); n = len(data); inds = arange(n); t0 = time() - # non-parametric bootstrap - for i in range(R): - t[i] = statistic(data[randint(0,n,n)]) - - # analysis - print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") - print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) - return t - - -mu, sigma = 100, 15 -datapoints = 10000 -x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample -t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data -n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) - -# add a 'best fit' line -y = mlab.normpdf( binsboot, mean(t), std(t)) -lt = plt.plot(binsboot, y, 'r--', linewidth=1) -plt.xlabel('Smarts') -plt.ylabel('Probability') -plt.axis([99.5, 100.6, 0, 3.0]) -plt.grid(True) - -plt.show() - -\end{minted} - - -% !split -\subsection{Code Example for Cross-validation and $k$-fold Cross-validation} - -The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import matplotlib.pyplot as plt -from sklearn.model_selection import KFold -from sklearn.linear_model import Ridge -from sklearn.model_selection import cross_val_score -from sklearn.preprocessing import PolynomialFeatures - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(3155) - -# Generate the data. -nsamples = 100 -x = np.random.randn(nsamples) -y = 3*x**2 + np.random.randn(nsamples) - -## Cross-validation on Ridge regression using KFold only - -# Decide degree on polynomial to fit -poly = PolynomialFeatures(degree = 6) - -# Decide which values of lambda to use -nlambdas = 500 -lambdas = np.logspace(-3, 5, nlambdas) - -# Initialize a KFold instance -k = 5 -kfold = KFold(n_splits = k) - -# Perform the cross-validation to estimate MSE -scores_KFold = np.zeros((nlambdas, k)) - -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - j = 0 - for train_inds, test_inds in kfold.split(x): - xtrain = x[train_inds] - ytrain = y[train_inds] - - xtest = x[test_inds] - ytest = y[test_inds] - - Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) - ridge.fit(Xtrain, ytrain[:, np.newaxis]) - - Xtest = poly.fit_transform(xtest[:, np.newaxis]) - ypred = ridge.predict(Xtest) - - scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) - - j += 1 - i += 1 - - -estimated_mse_KFold = np.mean(scores_KFold, axis = 1) - -## Cross-validation using cross_val_score from sklearn along with KFold - -# kfold is an instance initialized above as: -# kfold = KFold(n_splits = k) - -estimated_mse_sklearn = np.zeros(nlambdas) -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - - X = poly.fit_transform(x[:, np.newaxis]) - estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) - - # cross_val_score return an array containing the estimated negative mse for every fold. - # we have to the the mean of every array in order to get an estimate of the mse of the model - estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) - - i += 1 - -## Plot and compare the slightly different ways to perform cross-validation - -plt.figure() - -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') - -plt.xlabel('log10(lambda)') -plt.ylabel('mse') - -plt.legend() - -plt.show() - -\end{minted} - - -% !split -\subsection{The bias-variance tradeoff} - - -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset $\mathcal{L}$ consisting of the data -$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$. - -Let us assume that the true data is generated from a noisy model - -\[ -\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon} -\] - -where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$. - -In our derivation of the ordinary least squares method we defined then -an approximation to the function $f$ in terms of the parameters -$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model, -that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$. - -Thereafter we found the parameters $\bm{\beta}$ by optimizing the means squared error via the so-called cost function -\[ -C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]. -\] - -We can rewrite this as -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\sigma^2. -\] - -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error $\bm{\epsilon}$. - -To derive this equation, we need to recall that the variance of $\bm{y}$ and $\bm{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\bm{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\bm{\tilde{y}}$. -We use a more compact notation in terms of the expectation value -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}})^2\right], -\] -and adding and subtracting $\mathbb{E}\left[\bm{\tilde{y}}\right]$ we get -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}}+\mathbb{E}\left[\bm{\tilde{y}}\right]-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right], -\] -which, using the abovementioned expectation values can be rewritten as -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\bm{\tilde{y}}\right]+\sigma^2, -\] -that is the rewriting in terms of the so-called bias, the variance of the model $\bm{\tilde{y}}$ and the variance of $\bm{\epsilon}$. - - - - - -% !split -\subsection{Example code for Bias-Variance tradeoff} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 500 -n_boostraps = 100 -degree = 18 # A quite high value, just to show. -noise = 0.1 - -# Make data set. -x = np.linspace(-1, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) - -# Hold out some test data that is never used in training. -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -# Combine x transformation and model into one operation. -# Not neccesary, but convenient. -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - -# The following (m x n_bootstraps) matrix holds the column vectors y_pred -# for each bootstrap iteration. -y_pred = np.empty((y_test.shape[0], n_boostraps)) -for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - - # Evaluate the new model on the same test data each time. - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - -# Note: Expectations and variances taken w.r.t. different training -# data sets, hence the axis=1. Subsequent means are taken across the test data -# set in order to obtain a total value, but before this we have error/bias/variance -# calculated per data point in the test set. -# Note 2: The use of keepdims=True is important in the calculation of bias as this -# maintains the column vector form. Dropping this yields very unexpected results. -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) -print('Error:', error) -print('Bias^2:', bias) -print('Var:', variance) -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) - -plt.plot(x[::5, :], y[::5, :], label='f(x)') -plt.scatter(x_test, y_test, label='Data points') -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') -plt.legend() -plt.show() - -\end{minted} - - -% !split -\subsection{Understanding what happens} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 40 -n_boostraps = 100 -maxdegree = 14 - - -# Make data set. -x = np.linspace(-3, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) -error = np.zeros(maxdegree) -bias = np.zeros(maxdegree) -variance = np.zeros(maxdegree) -polydegree = np.zeros(maxdegree) -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -for degree in range(maxdegree): - model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - y_pred = np.empty((y_test.shape[0], n_boostraps)) - for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) - variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) - print('Polynomial degree:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) - -plt.plot(polydegree, np.log10(error), label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') -plt.legend() -plt.show() - - - - -\end{minted} - -% !split -\subsection{Summing up} - - - - -The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - - - -The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below $Var(\epsilon)$, the irreducible error. - - -What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - - -% !split -\subsection{Another Example rom Scikit-Learn's Repository} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -""" -============================ -Underfitting vs. Overfitting -============================ - -This example demonstrates the problems of underfitting and overfitting and -how we can use linear regression with polynomial features to approximate -nonlinear functions. The plot shows the function that we want to approximate, -which is a part of the cosine function. In addition, the samples from the -real function and the approximations of different models are displayed. The -models have polynomial features of different degrees. We can see that a -linear function (polynomial with degree 1) is not sufficient to fit the -training samples. This is called **underfitting**. A polynomial of degree 4 -approximates the true function almost perfectly. However, for higher degrees -the model will **overfit** the training data, i.e. it learns the noise of the -training data. -We evaluate quantitatively **overfitting** / **underfitting** by using -cross-validation. We calculate the mean squared error (MSE) on the validation -set, the higher, the less likely the model generalizes correctly from the -training data. -""" - -print(__doc__) - -import numpy as np -import matplotlib.pyplot as plt -from sklearn.pipeline import Pipeline -from sklearn.preprocessing import PolynomialFeatures -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import cross_val_score - - -def true_fun(X): - return np.cos(1.5 * np.pi * X) - -np.random.seed(0) - -n_samples = 30 -degrees = [1, 4, 15] - -X = np.sort(np.random.rand(n_samples)) -y = true_fun(X) + np.random.randn(n_samples) * 0.1 - -plt.figure(figsize=(14, 5)) -for i in range(len(degrees)): - ax = plt.subplot(1, len(degrees), i + 1) - plt.setp(ax, xticks=(), yticks=()) - - polynomial_features = PolynomialFeatures(degree=degrees[i], - include_bias=False) - linear_regression = LinearRegression() - pipeline = Pipeline([("polynomial_features", polynomial_features), - ("linear_regression", linear_regression)]) - pipeline.fit(X[:, np.newaxis], y) - - # Evaluate the models using crossvalidation - scores = cross_val_score(pipeline, X[:, np.newaxis], y, - scoring="neg_mean_squared_error", cv=10) - - X_test = np.linspace(0, 1, 100) - plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") - plt.plot(X_test, true_fun(X_test), label="True function") - plt.scatter(X, y, edgecolor='b', s=20, label="Samples") - plt.xlabel("x") - plt.ylabel("y") - plt.xlim((0, 1)) - plt.ylim((-2, 2)) - plt.legend(loc="best") - plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( - degrees[i], -scores.mean(), scores.std())) -plt.show() -\end{minted} - - - -% !split -\subsection{The one-dimensional Ising model} - -Let us bring back the Ising model again, but now with an additional -focus on Ridge and Lasso regression as well. We repeat some of the -basic parts of the Ising model and the setup of the training and test -data. The one-dimensional Ising model with nearest neighbor -interaction, no external field and a constant coupling constant $J$ is -given by - -\begin{align} - H = -J \sum_{k}^L s_k s_{k + 1}, -\end{align} -where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins in the system is determined by $L$. For the one-dimensional system there is no phase transition. - -We will look at a system of $L = 40$ spins with a coupling constant of $J = 1$. To get enough training data we will generate 10000 states with their respective energies. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import make_axes_locatable -import seaborn as sns -import scipy.linalg as scl -from sklearn.model_selection import train_test_split -import sklearn.linear_model as skl -import tqdm -sns.set(color_codes=True) -cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') - -L = 40 -n = int(1e4) - -spins = np.random.choice([-1, 1], size=(n, L)) -J = 1.0 - -energies = np.zeros(n) - -for i in range(n): - energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) -\end{minted} - -A more general form for the one-dimensional Ising model is - -\begin{align} - H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\end{align} - -Here we allow for interactions beyond the nearest neighbors and a more -adaptive coupling matrix. This latter expression can be formulated as -a matrix-product on the form -\begin{align} - H = X J, -\end{align} - -where $X_{jk} = s_j s_k$ and $J$ is the matrix consisting of the -elements $-J_{jk}$. This form of writing the energy fits perfectly -with the form utilized in linear regression, viz. -\begin{align} - \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}. -\end{align} -We organize the data as we did above -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X = np.zeros((n, L ** 2)) -for i in range(n): - X[i] = np.outer(spins[i], spins[i]).ravel() -y = energies -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96) - -X_train_own = np.concatenate( - (np.ones(len(X_train))[:, np.newaxis], X_train), - axis=1 -) - -X_test_own = np.concatenate( - (np.ones(len(X_test))[:, np.newaxis], X_test), - axis=1 -) -\end{minted} - -We will do all fitting with \textbf{Scikit-Learn}, - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -clf = skl.LinearRegression().fit(X_train, y_train) -\end{minted} -When extracting the $J$-matrix we make sure to remove the intercept -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -J_sk = clf.coef_.reshape(L, L) -\end{minted} -And then we plot the results -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_sk, **cmap_args) -plt.title("LinearRegression from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) -plt.show() -\end{minted} -The results perfectly with our previous discussion where we used our own code. - -% !split -\subsection{Ridge regression} - -Having explored the ordinary least squares we move on to ridge -regression. In ridge regression we include a \textbf{regularizer}. This -involves a new cost function which leads to a new estimate for the -weights $\bm{\beta}$. This results in a penalized regression problem. The -cost function is given by - -\begin{align} - C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \bm{\beta}^T\bm{\beta}. -\end{align} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -_lambda = 0.1 -clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train) -J_ridge_sk = clf_ridge.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_ridge_sk, **cmap_args) -plt.title("Ridge from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - -plt.show() -\end{minted} - -% !split -\subsection{LASSO regression} - -In the \textbf{Least Absolute Shrinkage and Selection Operator} (LASSO)-method we get a third cost function. - -\begin{align} - C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \sqrt{\bm{\beta}^T\bm{\beta}}. -\end{align} - -Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from \textbf{Scikit-Learn}. - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train) -J_lasso_sk = clf_lasso.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_lasso_sk, **cmap_args) -plt.title("Lasso from Scikit-learn", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - -plt.show() -\end{minted} - -It is quite striking how LASSO breaks the symmetry of the coupling -constant as opposed to ridge and OLS. We get a sparse solution with -$J_{j, j + 1} = -1$. - - - -% !split -\subsection{Performance as function of the regularization parameter} - -We see how the different models perform for a different set of values for $\lambda$. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -lambdas = np.logspace(-4, 5, 10) - -train_errors = { - "ols_sk": np.zeros(lambdas.size), - "ridge_sk": np.zeros(lambdas.size), - "lasso_sk": np.zeros(lambdas.size) -} - -test_errors = { - "ols_sk": np.zeros(lambdas.size), - "ridge_sk": np.zeros(lambdas.size), - "lasso_sk": np.zeros(lambdas.size) -} - -plot_counter = 1 - -fig = plt.figure(figsize=(32, 54)) - -for i, _lambda in enumerate(tqdm.tqdm(lambdas)): - for key, method in zip( - ["ols_sk", "ridge_sk", "lasso_sk"], - [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)] - ): - method = method.fit(X_train, y_train) - - train_errors[key][i] = method.score(X_train, y_train) - test_errors[key][i] = method.score(X_test, y_test) - - omega = method.coef_.reshape(L, L) - - plt.subplot(10, 5, plot_counter) - plt.imshow(omega, **cmap_args) - plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda)) - plot_counter += 1 - -plt.show() -\end{minted} - -We see that LASSO reaches a good solution for low -values of $\lambda$, but will "wither" when we increase $\lambda$ too -much. Ridge is more stable over a larger range of values for -$\lambda$, but eventually also fades away. - -% !split -\subsection{Finding the optimal value of $\lambda$} - -To determine which value of $\lambda$ is best we plot the accuracy of -the models when predicting the training and the testing set. We expect -the accuracy of the training set to be quite good, but if the accuracy -of the testing set is much lower this tells us that we might be -subject to an overfit model. The ideal scenario is an accuracy on the -testing set that is close to the accuracy of the training set. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -fig = plt.figure(figsize=(20, 14)) - -colors = { - "ols_sk": "r", - "ridge_sk": "y", - "lasso_sk": "c" -} - -for key in train_errors: - plt.semilogx( - lambdas, - train_errors[key], - colors[key], - label="Train {0}".format(key), - linewidth=4.0 - ) - -for key in test_errors: - plt.semilogx( - lambdas, - test_errors[key], - colors[key] + "--", - label="Test {0}".format(key), - linewidth=4.0 - ) -plt.legend(loc="best", fontsize=18) -plt.xlabel(r"$\lambda$", fontsize=18) -plt.ylabel(r"$R^2$", fontsize=18) -plt.tick_params(labelsize=18) -plt.show() -\end{minted} - -From the above figure we can see that LASSO with $\lambda = 10^{-2}$ -achieves a very good accuracy on the test set. This by far surpasses the -other models for all values of $\lambda$. - - - -% !split -\subsection{Further Exercises} - -\paragraph{Exercise 1.} -We will 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). -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -x = np.random.rand(100,1) -y = 5*x*x+0.1*np.random.randn(100,1) -\end{minted} - -\begin{enumerate} -\item Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial. - -\item Use thereafter \textbf{scikit-learn} (see again the examples in the regression slides) and compare with your own code. - -\item Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as -\end{enumerate} - -\noindent -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] - -You can use the functionality included in scikit-learn. If you feel -for it, you can use your own program and define functions which -compute the above two functions. Discuss the meaning of these -results. Try also to vary the coefficient in front of the added -stochastic noise term and discuss the quality of the fits. - - - - -\paragraph{Exercise 2, variance of the parameters $\beta$ in linear regression.} -Show that the variance of the parameters $\beta$ in the linear regression method (chapter 3, equation (3.8) of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}) is given as - -\[ -\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, -\] -with -\[ -\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, -\] -where we have assumed that we fit a function of degree $p-1$ (for example a polynomial in $x$). - - - -\paragraph{Exercise 3.} -This exercise is a continuation of exercise 1. 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. You can use the code under the Regression as an example on how to use the Ridge and the Lasso 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). -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -x = np.random.rand(100,1) -y = 5*x*x+0.1*np.random.randn(100,1) -\end{minted} - -\begin{enumerate} -\item Write your own code for the Ridge method and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 1. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. - -\item Repeat the above but using the functionality of \textbf{scikit-learn}. Compare your code with the results from \textbf{scikit-learn}. Remember to run with the same random numbers for generating $x$ and $y$. - -\item Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parametrizing 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 that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$) or use the functionality of \textbf{scikit-learn} and compute their variances. Discuss the results of these variances as functions - -\item Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results. - -\item Try to implement the cross-validation as well. - -\item Finally, using \textbf{scikit-learn} or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as -\end{enumerate} - -\noindent -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] -Discuss these quantities as functions of the variable $\lambda$ in the Ridge and Lasso regression methods. - -\paragraph{Exercise 4.} -We will study how -to fit polynomials to a specific two-dimensional function called -\href{{http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf}}{Franke's -function}. This -is a function which has been widely used when testing various interpolation and fitting -algorithms. Furthermore, after having established the model and the -method, we will employ resamling techniques such as the cross-validation and/or -the bootstrap methods, in order to perform a proper assessment of our models. - - -The Franke function, which is a weighted sum of four exponentials reads as follows -\begin{align*} -f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ -&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. -\end{align*} - -The function will be defined for $x,y\in [0,1]$. Our first step will -be to perform an OLS regression analysis of this function, trying out -a polynomial fit with an $x$ and $y$ dependence of the form $[x, y, -x^2, y^2, xy, \dots]$. We will also include cross-validation and -bootstrap as resampling techniques. As in homeworks 1 and 2, we -can use a uniform distribution to set up the arrays of values for $x$ -and $y$, or as in the example below just a fix values for $x$ and $y$ with a given step size. -In this case we will have two predictors and need to fit a -function (for example a polynomial) of $x$ and $y$. Thereafter we will -repeat much of the same procedure using the the Ridge and -Lasso regression methods, introducing thus a dependence on the bias -(penalty) $\lambda$. - - -The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from mpl_toolkits.mplot3d import Axes3D -import matplotlib.pyplot as plt -from matplotlib import cm -from matplotlib.ticker import LinearLocator, FormatStrFormatter -import numpy as np -from random import random, seed - -fig = plt.figure() -ax = fig.gca(projection='3d') - -# Make data. -x = np.arange(0, 1, 0.05) -y = np.arange(0, 1, 0.05) -x, y = np.meshgrid(x,y) - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -z = FrankeFunction(x, y) - -# Plot the surface. -surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm, - linewidth=0, antialiased=False) - -# Customize the z axis. -ax.set_zlim(-0.10, 1.40) -ax.zaxis.set_major_locator(LinearLocator(10)) -ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) - -# Add a color bar which maps values to colors. -fig.colorbar(surf, shrink=0.5, aspect=5) - -plt.show() - -\end{minted} - - -We will thus again generate our own dataset for a function $\mathrm{FrankeFunction}(x,y)$ where -$x,y \in [0,1]$ could be defined by random numbers computed with the uniform -distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition -an added stochastic noise to this function using the normal distribution $\cal{N}(0,1)$. - -Write your own code (using either a matrix inversion or a singular value decomposition from e.g., \textbf{numpy} ) or use your code from exercises 1 and 3 -and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\beta$ by computing their variances, evaluate the Mean Squared error (MSE) -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -where we have defined the mean value of $\hat{y}$ as -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] - -Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm -and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models. - - -Write then your own code for the Ridge method, either using matrix -inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the -previous exercise (for the same polynomials and include resampling -techniques) but now for different values of $\lambda$. Compare and -analyze your results with those obtained with standard OLS. Study the -dependence on $\lambda$ while also varying eventually the strength of -the noise in your expression for $\mathrm{FrankeFunction}(x,y)$. - -Then perform the same studies but now with Lasso regression. Use the functionalities of -\textbf{scikit-learn}. Give a critical discussion of the three methods and a -judgement of which model fits the data best. - - -% ------------------- end of main content --------------- - -\end{document} - diff --git a/doc/src/Regression/_minted-Regression/default.pygstyle b/doc/src/Regression/_minted-Regression/default.pygstyle deleted file mode 100644 index e69de29bb..000000000 diff --git a/doc/src/Regression/ipynb-Regression-src.tar.gz b/doc/src/Regression/ipynb-Regression-src.tar.gz deleted file mode 100644 index 69eb49f3d..000000000 Binary files a/doc/src/Regression/ipynb-Regression-src.tar.gz and /dev/null differ diff --git a/doc/src/Regression/reveal.js/.gitignore b/doc/src/Regression/reveal.js/.gitignore deleted file mode 100644 index a5df3133d..000000000 --- a/doc/src/Regression/reveal.js/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -.DS_Store -.svn -log/*.log -tmp/** -node_modules/ -.sass-cache -css/reveal.min.css -js/reveal.min.js diff --git a/doc/src/Regression/reveal.js/.travis.yml b/doc/src/Regression/reveal.js/.travis.yml deleted file mode 100644 index 165d9ae9f..000000000 --- a/doc/src/Regression/reveal.js/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.10 -before_script: - - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/src/Regression/reveal.js/CONTRIBUTING.md b/doc/src/Regression/reveal.js/CONTRIBUTING.md deleted file mode 100644 index c2091e88f..000000000 --- a/doc/src/Regression/reveal.js/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -## Contributing - -Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. - - -### Personal Support -If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). - - -### Bug Reports -When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. - - -### Pull Requests -- Should follow the coding style of the file you work in, most importantly: - - Tabs to indent - - Single-quoted strings -- Should be made towards the **dev branch** -- Should be submitted from a feature/topic branch (not your master) - - -### Plugins -Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/src/Regression/reveal.js/Gruntfile.js b/doc/src/Regression/reveal.js/Gruntfile.js deleted file mode 100644 index b257e8f32..000000000 --- a/doc/src/Regression/reveal.js/Gruntfile.js +++ /dev/null @@ -1,140 +0,0 @@ -/* global module:false */ -module.exports = function(grunt) { - var port = grunt.option('port') || 8000; - // Project configuration - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - meta: { - banner: - '/*!\n' + - ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + - ' * http://lab.hakim.se/reveal-js\n' + - ' * MIT licensed\n' + - ' *\n' + - ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + - ' */' - }, - - qunit: { - files: [ 'test/*.html' ] - }, - - uglify: { - options: { - banner: '<%= meta.banner %>\n' - }, - build: { - src: 'js/reveal.js', - dest: 'js/reveal.min.js' - } - }, - - cssmin: { - compress: { - files: { - 'css/reveal.min.css': [ 'css/reveal.css' ] - } - } - }, - - sass: { - main: { - files: { - 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', - 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', - 'css/theme/cbc.css': 'css/theme/source/cbc.scss', - 'css/theme/default.css': 'css/theme/source/default.scss', - 'css/theme/beige.css': 'css/theme/source/beige.scss', - 'css/theme/night.css': 'css/theme/source/night.scss', - 'css/theme/serif.css': 'css/theme/source/serif.scss', - 'css/theme/simple.css': 'css/theme/source/simple.scss', - 'css/theme/sky.css': 'css/theme/source/sky.scss', - 'css/theme/moon.css': 'css/theme/source/moon.scss', - 'css/theme/solarized.css': 'css/theme/source/solarized.scss', - 'css/theme/blood.css': 'css/theme/source/blood.scss' - } - } - }, - - jshint: { - options: { - curly: false, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - eqnull: true, - browser: true, - expr: true, - globals: { - head: false, - module: false, - console: false, - unescape: false - } - }, - files: [ 'Gruntfile.js', 'js/reveal.js' ] - }, - - connect: { - server: { - options: { - port: port, - base: '.' - } - } - }, - - zip: { - 'reveal-js-presentation.zip': [ - 'index.html', - 'css/**', - 'js/**', - 'lib/**', - 'images/**', - 'plugin/**' - ] - }, - - watch: { - main: { - files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], - tasks: 'default' - }, - theme: { - files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], - tasks: 'themes' - } - } - - }); - - // Dependencies - grunt.loadNpmTasks( 'grunt-contrib-qunit' ); - grunt.loadNpmTasks( 'grunt-contrib-jshint' ); - grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); - grunt.loadNpmTasks( 'grunt-contrib-uglify' ); - grunt.loadNpmTasks( 'grunt-contrib-watch' ); - grunt.loadNpmTasks( 'grunt-contrib-sass' ); - grunt.loadNpmTasks( 'grunt-contrib-connect' ); - grunt.loadNpmTasks( 'grunt-zip' ); - - // Default task - grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); - - // Theme task - grunt.registerTask( 'themes', [ 'sass' ] ); - - // Package presentation to archive - grunt.registerTask( 'package', [ 'default', 'zip' ] ); - - // Serve presentation locally - grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); - - // Run tests - grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); - -}; diff --git a/doc/src/Regression/reveal.js/LICENSE b/doc/src/Regression/reveal.js/LICENSE deleted file mode 100644 index 09623076f..000000000 --- a/doc/src/Regression/reveal.js/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2015 Hakim El Hattab, http://hakim.se - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/doc/src/Regression/reveal.js/README.md b/doc/src/Regression/reveal.js/README.md deleted file mode 100644 index 573b19597..000000000 --- a/doc/src/Regression/reveal.js/README.md +++ /dev/null @@ -1,1052 +0,0 @@ -# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) - -A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). - -reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. - - -#### More reading: -- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. -- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. -- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! -- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. -- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. - -## Online Editor - -Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). - - -## Instructions - -### Markup - -Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: - -```html -
-
-
Single Horizontal Slide
-
-
Vertical Slide 1
-
Vertical Slide 2
-
-
-
-``` - -### Markdown - -It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` -
-``` - -#### External Markdown - -You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. - -When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). - -```html -
-
-``` - -#### Element Attributes - -Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. - -```html -
- -
-``` - -#### Slide Attributes - -Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. - -```html -
- -
-``` - - -### Configuration - -At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. - -```javascript -Reveal.initialize({ - - // Display controls in the bottom right corner - controls: true, - - // Display a presentation progress bar - progress: true, - - // Display the page number of the current slide - slideNumber: false, - - // Push each slide change to the browser history - history: false, - - // Enable keyboard shortcuts for navigation - keyboard: true, - - // Enable the slide overview mode - overview: true, - - // Vertical centering of slides - center: true, - - // Enables touch navigation on devices with touch input - touch: true, - - // Loop the presentation - loop: false, - - // Change the presentation direction to be RTL - rtl: false, - - // Turns fragments on and off globally - fragments: true, - - // Flags if the presentation is running in an embedded mode, - // i.e. contained within a limited portion of the screen - embedded: false, - - // Flags if we should show a help overlay when the questionmark - // key is pressed - help: true, - - // Number of milliseconds between automatically proceeding to the - // next slide, disabled when set to 0, this value can be overwritten - // by using a data-autoslide attribute on your slides - autoSlide: 0, - - // Stop auto-sliding after user input - autoSlideStoppable: true, - - // Enable slide navigation via mouse wheel - mouseWheel: false, - - // Hides the address bar on mobile devices - hideAddressBar: true, - - // Opens links in an iframe preview overlay - previewLinks: false, - - // Transition style - transition: 'default', // none/fade/slide/convex/concave/zoom - - // Transition speed - transitionSpeed: 'default', // default/fast/slow - - // Transition style for full page slide backgrounds - backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom - - // Number of slides away from the current that are visible - viewDistance: 3, - - // Parallax background image - parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - - // Amount to move parallax background (horizontal and vertical) on slide change - // Number, e.g. 100 - parallaxBackgroundHorizontal: '', - parallaxBackgroundVertical: '' - -}); -``` - - -The configuration can be updated after initialization using the ```configure``` method: - -```javascript -// Turn autoSlide off -Reveal.configure({ autoSlide: 0 }); - -// Start auto-sliding every 5s -Reveal.configure({ autoSlide: 5000 }); -``` - - -### Dependencies - -Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: - -```javascript -Reveal.initialize({ - dependencies: [ - // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ - { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, - - // Interpret Markdown in
elements - { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - - // Syntax highlight for elements - { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, - - // Zoom in and out with Alt+click - { src: 'plugin/zoom-js/zoom.js', async: true }, - - // Speaker notes - { src: 'plugin/notes/notes.js', async: true }, - - // Remote control your reveal.js presentation using a touch device - { src: 'plugin/remotes/remotes.js', async: true }, - - // MathJax - { src: 'plugin/math/math.js', async: true } - ] -}); -``` - -You can add your own extensions using the same syntax. The following properties are available for each dependency object: -- **src**: Path to the script to load -- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false -- **callback**: [optional] Function to execute when the script has loaded -- **condition**: [optional] Function which must return true for the script to be loaded - - -### Ready Event - -A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. - -```javascript -Reveal.addEventListener( 'ready', function( event ) { - // event.currentSlide, event.indexh, event.indexv -} ); -``` - - -### Presentation Size - -All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. - -See below for a list of configuration options related to sizing, including default values: - -```javascript -Reveal.initialize({ - - ... - - // The "normal" size of the presentation, aspect ratio will be preserved - // when the presentation is scaled to fit different resolutions. Can be - // specified using percentage units. - width: 960, - height: 700, - - // Factor of the display size that should remain empty around the content - margin: 0.1, - - // Bounds for smallest/largest possible scale to apply to content - minScale: 0.2, - maxScale: 1.5 - -}); -``` - - -### Auto-sliding - -Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: - -```javascript -// Slide every five seconds -Reveal.configure({ - autoSlide: 5000 -}); -``` -When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. - -You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: - -```html -
-

After 2 seconds the first fragment will be shown.

-

After 10 seconds the next fragment will be shown.

-

Now, the fragment is displayed for 2 seconds before the next slide is shown.

-
-``` - -Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. - - -### Keyboard Bindings - -If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: - -```javascript -Reveal.configure({ - keyboard: { - 13: 'next', // go to the next slide when the ENTER key is pressed - 27: function() {}, // do something custom when ESC is pressed - 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) - } -}); -``` - -### Lazy Loading - -When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. - -To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. - -```html -
- - - -
-``` - - -### API - -The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: - -```javascript -// Navigation -Reveal.slide( indexh, indexv, indexf ); -Reveal.left(); -Reveal.right(); -Reveal.up(); -Reveal.down(); -Reveal.prev(); -Reveal.next(); -Reveal.prevFragment(); -Reveal.nextFragment(); - -// Toggle presentation states, optionally pass true/false to force on/off -Reveal.toggleOverview(); -Reveal.togglePause(); -Reveal.toggleAutoSlide(); - -// Change a config value at runtime -Reveal.configure({ controls: true }); - -// Returns the present configuration options -Reveal.getConfig(); - -// Fetch the current scale of the presentation -Reveal.getScale(); - -// Retrieves the previous and current slide elements -Reveal.getPreviousSlide(); -Reveal.getCurrentSlide(); - -Reveal.getIndices(); // { h: 0, v: 0 } } -Reveal.getProgress(); // 0-1 -Reveal.getTotalSlides(); - -// State checks -Reveal.isFirstSlide(); -Reveal.isLastSlide(); -Reveal.isOverview(); -Reveal.isPaused(); -Reveal.isAutoSliding(); -``` - -### Slide Changed Event - -A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. - -Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. - -```javascript -Reveal.addEventListener( 'slidechanged', function( event ) { - // event.previousSlide, event.currentSlide, event.indexh, event.indexv -} ); -``` - -### Presentation State - -The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. - -```javascript -Reveal.slide( 1 ); -// we're on slide 1 - -var state = Reveal.getState(); - -Reveal.slide( 3 ); -// we're on slide 3 - -Reveal.setState( state ); -// we're back on slide 1 -``` - -### Slide States - -If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. - -Furthermore you can also listen to these changes in state via JavaScript: - -```javascript -Reveal.addEventListener( 'somestate', function() { - // TODO: Sprinkle magic -}, false ); -``` - -### Slide Backgrounds - -Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. - -```html -
-

All CSS color formats are supported, like rgba() or hsl().

-
-
-

This slide will have a full-size background image.

-
-
-

This background image will be sized to 100px and repeated.

-
-
-

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

-
-
-

Embeds a web page as a background. Note that the page won't be interactive.

-
-``` - -Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. - - -### Parallax Background - -If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). - -```javascript -Reveal.initialize({ - - // Parallax background image - parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) - - // Amount of pixels to move the parallax background per slide step, - // a value of 0 disables movement along the given axis - // These are optional, if they aren't specified they'll be calculated automatically - parallaxBackgroundHorizontal: 200, - parallaxBackgroundVertical: 50 - -}); -``` - -Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). - - - -### Slide Transitions -The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: - -```html -
-

This slide will override the presentation transition and zoom!

-
- -
-

Choose from three transition speeds: default, fast or slow!

-
-``` - -You can also use different in and out transitions for the same slide: - -```html -
- The train goes on … -
-
- and on … -
-
- and stops. -
-
- (Passengers entering and leaving) -
-
- And it starts again. -
-``` - - -Note that this does not work with the page and cube transitions. - - -### Internal links - -It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): - -```html -Link -Link -``` - -You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. - -```html - - - - - - -``` - - -### Fragments -Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments - -The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: - -```html -
-

grow

-

shrink

-

fade-out

-

visible only once

-

blue only once

-

highlight-red

-

highlight-green

-

highlight-blue

-
-``` - -Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. - -```html -
- - I'll fade in, then out - -
-``` - -The display order of fragments can be controlled using the ```data-fragment-index``` attribute. - -```html -
-

Appears last

-

Appears first

-

Appears second

-
-``` - -### Fragment events - -When a slide fragment is either shown or hidden reveal.js will dispatch an event. - -Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. - -```javascript -Reveal.addEventListener( 'fragmentshown', function( event ) { - // event.fragment = the fragment DOM element -} ); -Reveal.addEventListener( 'fragmenthidden', function( event ) { - // event.fragment = the fragment DOM element -} ); -``` - -### Code syntax highlighting - -By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. - -```html -
-

-(def lazy-fib
-  (concat
-   [0 1]
-   ((fn rfib [a b]
-        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
-	
-
-``` - -### Slide number -If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. - -```javascript -// Shows the slide number using default formatting -Reveal.configure({ slideNumber: true }); - -// Slide number formatting can be configured using these variables: -// h: current slide's horizontal index -// v: current slide's vertical index -// c: current slide index (flattened) -// t: total number of slides (flattened) -Reveal.configure({ slideNumber: 'c / t' }); - -``` - - -### Overview mode - -Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, -as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: - -```javascript -Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); -Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); - -// Toggle the overview mode programmatically -Reveal.toggleOverview(); -``` - -### Fullscreen mode -Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. - - -### Embedded media -Embedded HTML5 `