Files
FYS-STK4155/doc/LectureNotes/chapter3.ipynb
T
Morten Hjorth-Jensen 759aa14da5 test
2021-03-28 22:16:58 -04:00

1379 lines
47 KiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Ridge and Lasso Regression\n",
"\n",
"[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage)\n",
"\n",
"\n",
"## The singular value decomposition\n",
"\n",
"The examples we have looked at so far are cases where we normally can\n",
"invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion 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. Obtaining the inverse of the design matrix is then often done via a so-called LU, QR or Cholesky decomposition. \n",
"\n",
"\n",
"\n",
"This may\n",
"however not the be case in general and a standard matrix inversion\n",
"algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n",
"\n",
"There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions. \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",
"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",
"If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"_auto1\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
"\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
"\\label{_auto1} \\tag{1}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"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",
"\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",
"\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 $m\\times n$\n",
"and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
"dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
"We have then"
]
},
{
"cell_type": "markdown",
"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",
"The SVD\n",
"decomposition (singular values) gives eigenvalues \n",
"$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
"eigenvalues (singular values) are zero.\n",
"\n",
"In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
"$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
"orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
"and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
"singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
"the rest of the matrix. There are at most $p$ singular values\n",
"assuming that $n > p$. In our regression examples for the nuclear\n",
"masses and the equation of state this is indeed the case, while for\n",
"the Ising model we have $p > n$. These are often cases that lead to\n",
"near singular or singular matrices.\n",
"\n",
"The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"# SVD inversion\n",
"def SVDinv(A):\n",
" ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
" SVD is numerically more stable than the inversion algorithms provided by\n",
" numpy and scipy.linalg at the cost of being slower.\n",
" '''\n",
" U, s, VT = np.linalg.svd(A)\n",
"# print('test U')\n",
"# print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
"# print('test VT')\n",
"# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
" print(U)\n",
" print(s)\n",
" print(VT)\n",
"\n",
" D = np.zeros((len(U),len(VT)))\n",
" for i in range(0,len(VT)):\n",
" D[i,i]=s[i]\n",
" UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n",
" return np.matmul(V,np.matmul(invD,UT))\n",
"\n",
"\n",
"X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n",
"print(X)\n",
"A = np.transpose(X) @ X\n",
"print(A)\n",
"# Brute force inversion of super-collinear matrix\n",
"#B = np.linalg.inv(A)\n",
"#print(B)\n",
"C = SVDinv(A)\n",
"print(C)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
"column is the row-wise sum of the other two columns. The rank of a\n",
"matrix (the column rank) is the dimension of space spanned by the\n",
"column vectors. The rank of the matrix is the number of linearly\n",
"independent columns, in this case just $2$. We see this from the\n",
"singular values when running the above code. Running the standard\n",
"inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
"in the program terminating due to a singular matrix.\n",
"\n",
"\n",
"\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",
"$$ \\tilde{y}^{OLS}=\\boldsymbol{X}\\hat{\\beta}^{OLS}=\\sum_{j=1}^p \\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y}$$ and for Ridge we have \n",
"\n",
"$$ \\tilde{y}^{Ridge}=\\boldsymbol{X}\\hat{\\beta}^{Ridge}=\\sum_{j=1}^p \\boldsymbol{u}_j\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{u}_j^T\\boldsymbol{y}$$ . \n",
"\n",
"It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$. \n",
"\n",
"Here we have that $$\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T$$, with $$\\Sigma$$ being an $$ n\\times p$$ matrix and $$\\boldsymbol{V}$$ being a $$ p\\times p$$ matrix. We also have assumed here that $$ n > p$$. \n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Ridge and LASSO Regression\n",
"\n",
"[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage)\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": [
"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 tradeoff \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",
"\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",
"\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",
"\n",
"\n",
"## A better understanding of regularization\n",
"\n",
"The parameter $\\lambda$ that we have introduced in the Ridge (and\n",
"Lasso as well) regression is often called a regularization parameter\n",
"or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?\n",
"\n",
"Here we will first look at how to analyze the difference between the\n",
"standard OLS equations and the Ridge expressions in terms of a linear\n",
"algebra analysis using the SVD algorithm. Thereafter, we will link\n",
"(see the material on the bias-variance tradeoff below) these\n",
"observation to the statisical analysis of the results. In particular\n",
"we consider how the variance of the parameters $\\boldsymbol{\\beta}$ is\n",
"affected by changing the parameter $\\lambda$.\n",
"\n",
"\n",
"We have our design matrix\n",
" $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. With the SVD we decompose it as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{X} = \\boldsymbol{U\\Sigma V^T},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with $\\boldsymbol{U}\\in {\\mathbb{R}}^{n\\times n}$, $\\boldsymbol{\\Sigma}\\in {\\mathbb{R}}^{n\\times p}$\n",
"and $\\boldsymbol{V}\\in {\\mathbb{R}}^{p\\times p}$.\n",
"\n",
"The matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ and $\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{I}$.\n",
"\n",
"\n",
"\n",
"## Introducing the Covariance and Correlation functions\n",
"\n",
"Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n",
"the definition of the covariance and the correlation function. These are quantities \n",
"\n",
"Suppose we have defined two vectors\n",
"$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
" \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
" \\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where for example"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With this definition and recalling that the variance is defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we can rewrite the covariance matrix as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
" \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
" \\end{bmatrix}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The covariance takes values between zero and infinity and may thus\n",
"lead to problems with loss of numerical precision for particularly\n",
"large values. It is common to scale the covariance matrix by\n",
"introducing instead the correlation matrix defined via the so-called\n",
"correlation function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
"\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
"can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
"and $\\boldsymbol{y}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
" \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
" \\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above example this is the function we constructed using **pandas**.\n",
"\n",
"\n",
"\n",
"In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
"we defined the design/feature matrix $\\boldsymbol{X}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix}\n",
"x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
"x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
"x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
"\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
"x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
"x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
"\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
"entries $n$ being the row elements.\n",
"We can rewrite the design/feature matrix in terms of its column vectors as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with a given vector"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With these definitions, we can now rewrite our $2\\times 2$\n",
"correaltion/covariance matrix in terms of a moe general design/feature\n",
"matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
"covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
"\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
"\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n",
"\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and the correlation matrix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
"1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
"\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n",
"\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Numpy function **np.cov** calculates the covariance elements using\n",
"the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
"the exact mean values. The following simple function uses the\n",
"**np.vstack** function which takes each vector of dimension $1\\times n$\n",
"and produces a $2\\times n$ matrix $\\boldsymbol{W}$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n",
" x_1 & y_1 \\\\\n",
" x_2 & y_2\\\\\n",
" \\dots & \\dots \\\\\n",
" x_{n-2} & y_{n-2}\\\\\n",
" x_{n-1} & y_{n-1} & \n",
" \\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which in turn is converted into into the $2\\times 2$ covariance matrix\n",
"$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
"the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
"function **np.mean(x)**. We can also extract the eigenvalues of the\n",
"covariance matrix through the **np.linalg.eig()** function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Importing various packages\n",
"import numpy as np\n",
"n = 100\n",
"x = np.random.normal(size=n)\n",
"print(np.mean(x))\n",
"y = 4+3*x+np.random.normal(size=n)\n",
"print(np.mean(y))\n",
"W = np.vstack((x, y))\n",
"C = np.cov(W)\n",
"print(C)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The previous example can be converted into the correlation matrix by\n",
"simply scaling the matrix elements with the variances. We should also\n",
"subtract the mean values for each column. This leads to the following\n",
"code which sets up the correlations matrix for the previous example in\n",
"a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"n = 100\n",
"# define two vectors \n",
"x = np.random.random(size=n)\n",
"y = 4+3*x+np.random.normal(size=n)\n",
"#scaling the x and y vectors \n",
"x = x - np.mean(x)\n",
"y = y - np.mean(y)\n",
"variance_x = np.sum(x@x)/n\n",
"variance_y = np.sum(y@y)/n\n",
"print(variance_x)\n",
"print(variance_y)\n",
"cov_xy = np.sum(x@y)/n\n",
"cov_xx = np.sum(x@x)/n\n",
"cov_yy = np.sum(y@y)/n\n",
"C = np.zeros((2,2))\n",
"C[0,0]= cov_xx/variance_x\n",
"C[1,1]= cov_yy/variance_y\n",
"C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
"C[1,0]= C[0,1]\n",
"print(C)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that the matrix elements along the diagonal are one as they\n",
"should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
"this matrix we easily see that it is a positive definite matrix.\n",
"\n",
"The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
"\n",
"\n",
"We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"n = 10\n",
"x = np.random.normal(size=n)\n",
"x = x - np.mean(x)\n",
"y = 4+3*x+np.random.normal(size=n)\n",
"y = y - np.mean(y)\n",
"X = (np.vstack((x, y))).T\n",
"print(X)\n",
"Xpd = pd.DataFrame(X)\n",
"print(Xpd)\n",
"correlation_matrix = Xpd.corr()\n",
"print(correlation_matrix)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We expand this model to the Franke function discussed above."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Common imports\n",
"import numpy as np\n",
"import pandas as pd\n",
"\n",
"\n",
"def FrankeFunction(x,y):\n",
"\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
"\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
"\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
"\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
"\treturn term1 + term2 + term3 + term4\n",
"\n",
"\n",
"def create_X(x, y, n ):\n",
"\tif len(x.shape) > 1:\n",
"\t\tx = np.ravel(x)\n",
"\t\ty = np.ravel(y)\n",
"\n",
"\tN = len(x)\n",
"\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
"\tX = np.ones((N,l))\n",
"\n",
"\tfor i in range(1,n+1):\n",
"\t\tq = int((i)*(i+1)/2)\n",
"\t\tfor k in range(i+1):\n",
"\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
"\n",
"\treturn X\n",
"\n",
"\n",
"# Making meshgrid of datapoints and compute Franke's function\n",
"n = 4\n",
"N = 100\n",
"x = np.sort(np.random.uniform(0, 1, N))\n",
"y = np.sort(np.random.uniform(0, 1, N))\n",
"z = FrankeFunction(x, y)\n",
"X = create_X(x, y, n=n) \n",
"\n",
"Xpd = pd.DataFrame(X)\n",
"# subtract the mean values and set up the covariance matrix\n",
"Xpd = Xpd - Xpd.mean()\n",
"covariance_matrix = Xpd.cov()\n",
"print(covariance_matrix)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We note here that the covariance is zero for the first rows and\n",
"columns since all matrix elements in the design matrix were set to one\n",
"(we are fitting the function in terms of a polynomial of degree $n$).\n",
"\n",
"This means that the variance for these elements will be zero and will\n",
"cause problems when we set up the correlation matrix. We can simply\n",
"drop these elements and construct a correlation\n",
"matrix without these elements. \n",
"\n",
"\n",
"\n",
"\n",
"We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix}\n",
"x_{00} & x_{01}\\\\\n",
"x_{10} & x_{11}\\\\\n",
"\\end{bmatrix}=\\begin{bmatrix}\n",
"\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
"\\end{bmatrix}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we then compute the expectation value"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
"x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n",
"x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n",
"\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which is just"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n",
" \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
" \\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
"\n",
"It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
"\n",
"\n",
"## Linking with SVD"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}