Files
FYS-STK4155/doc/pub/week36/html/week36.html
T
Morten Hjorth-Jensen b7307fb7aa small typos in week36
2021-09-16 05:37:28 +02:00

2140 lines
126 KiB
HTML

<!--
Automatically generated HTML file from DocOnce source
(https://github.com/doconce/doconce/)
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/doconce/doconce/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Week 36: Statistical interpretation of Linear Regression and Resampling techniques">
<title>Week 36: Statistical interpretation of Linear Regression and Resampling techniques</title>
<style type="text/css">
/* bloodish style */
body {
font-family: Helvetica, Verdana, Arial, Sans-serif;
color: #404040;
background: #ffffff;
}
h1 { font-size: 1.8em; color: #8A0808; }
h2 { font-size: 1.6em; color: #8A0808; }
h3 { font-size: 1.4em; color: #8A0808; }
h4 { color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
/* pre style removed because it will interfer with pygments */
p { text-indent: 0px; }
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-style: normal; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa}
.alert-text-small { font-size: 80%; }
.alert-text-large { font-size: 130%; }
.alert-text-normal { font-size: 90%; }
.alert {
padding:8px 35px 8px 14px; margin-bottom:18px;
text-shadow:0 1px 0 rgba(255,255,255,0.5);
border:1px solid #bababa;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
color: #555;
background-color: #f8f8f8;
background-position: 10px 5px;
background-repeat: no-repeat;
background-size: 38px;
padding-left: 55px;
width: 75%;
}
.alert-block {padding-top:14px; padding-bottom:14px}
.alert-block > p, .alert-block > ul {margin-bottom:1em}
.alert li {margin-top: 1em}
.alert-block p+p {margin-top:5px}
.alert-notice { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_notice.png); }
.alert-summary { background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_summary.png); }
.alert-warning { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_warning.png); }
.alert-question {background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_question.png); }
div { text-align: justify; text-justify: inter-word; }
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 36', 2, None, 'plans-for-week-36'),
('Thursday September 9', 2, None, 'thursday-september-9'),
('Summary from last Week and Examples',
2,
None,
'summary-from-last-week-and-examples'),
('Linear Regression and the SVD',
2,
None,
'linear-regression-and-the-svd'),
('What does it mean?', 2, None, 'what-does-it-mean'),
('And finally $\\boldsymbol{X}\\boldsymbol{X}^T$',
2,
None,
'and-finally-boldsymbol-x-boldsymbol-x-t'),
('Code for SVD and Inversion of Matrices',
2,
None,
'code-for-svd-and-inversion-of-matrices'),
('Inverse of Rectangular Matrix',
2,
None,
'inverse-of-rectangular-matrix'),
('Ridge and LASSO Regression',
2,
None,
'ridge-and-lasso-regression'),
('From OLS to Ridge and Lasso',
2,
None,
'from-ols-to-ridge-and-lasso'),
('Deriving the Ridge Regression Equations',
2,
None,
'deriving-the-ridge-regression-equations'),
('SVD analysis', 2, None, 'svd-analysis'),
('Interpreting the Ridge results',
2,
None,
'interpreting-the-ridge-results'),
('More interpretations', 2, None, 'more-interpretations'),
('Deriving the Lasso Regression Equations',
2,
None,
'deriving-the-lasso-regression-equations'),
('Simple example to illustrate Ordinary Least Squares, Ridge and '
'Lasso Regression',
2,
None,
'simple-example-to-illustrate-ordinary-least-squares-ridge-and-lasso-regression'),
('Ridge Regression', 2, None, 'ridge-regression'),
('Lasso Regression', 2, None, 'lasso-regression'),
('Yet another Example', 2, None, 'yet-another-example'),
('The OLS case', 2, None, 'the-ols-case'),
('The Ridge case', 2, None, 'the-ridge-case'),
('Writing the Cost Function',
2,
None,
'writing-the-cost-function'),
('Lasso case', 2, None, 'lasso-case'),
('The first Case', 2, None, 'the-first-case'),
('Simple code for solving the above problem',
2,
None,
'simple-code-for-solving-the-above-problem'),
('With Lasso Regression', 2, None, 'with-lasso-regression'),
('Another Example, now with a polynomial fit',
2,
None,
'another-example-now-with-a-polynomial-fit'),
('Using CVXOPT', 2, None, 'using-cvxopt'),
('The simpler Example', 2, None, 'the-simpler-example'),
('Friday September 10', 2, None, 'friday-september-10'),
('Linking the regression analysis with a statistical '
'interpretation',
2,
None,
'linking-the-regression-analysis-with-a-statistical-interpretation'),
('Assumptions made', 2, None, 'assumptions-made'),
('Expectation value and variance',
2,
None,
'expectation-value-and-variance'),
('Expectation value and variance for $\\boldsymbol{\\beta}$',
2,
None,
'expectation-value-and-variance-for-boldsymbol-beta'),
('Deriving OLS from a probability distribution',
2,
None,
'deriving-ols-from-a-probability-distribution'),
('Independent and Identically Distrubuted (iid)',
2,
None,
'independent-and-identically-distrubuted-iid'),
('Maximum Likelihood Estimation (MLE)',
2,
None,
'maximum-likelihood-estimation-mle'),
('A new Cost Function', 2, None, 'a-new-cost-function'),
("More basic Statistics and Bayes' theorem",
2,
None,
'more-basic-statistics-and-bayes-theorem'),
('Marginal Probability', 2, None, 'marginal-probability'),
('Conditional Probability', 2, None, 'conditional-probability'),
("Bayes' Theorem", 2, None, 'bayes-theorem'),
("Interpretations of Bayes' Theorem",
2,
None,
'interpretations-of-bayes-theorem'),
("Example of Usage of Bayes' theorem",
2,
None,
'example-of-usage-of-bayes-theorem'),
('Doing it correctly', 2, None, 'doing-it-correctly'),
("Bayes' Theorem and Ridge and Lasso Regression",
2,
None,
'bayes-theorem-and-ridge-and-lasso-regression'),
('Test Function for what happens with OLS, Ridge and Lasso',
2,
None,
'test-function-for-what-happens-with-ols-ridge-and-lasso'),
("Invoking Bayes' theorem", 2, None, 'invoking-bayes-theorem'),
('Ridge and Bayes', 2, None, 'ridge-and-bayes'),
('Lasso and Bayes', 2, None, 'lasso-and-bayes')]}
end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "AMS" },
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
}
});
</script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- ------------------- main content ---------------------- -->
<center><h1>Week 36: Statistical interpretation of Linear Regression and Resampling techniques</h1></center> <!-- document title -->
<p>
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<p>
<!-- institution(s) -->
<center>[1] <b>Department of Physics, University of Oslo</b></center>
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Sep 16, 2021</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plans-for-week-36">Plans for week 36 </h2>
<ul>
<li> Thursday: Summary from last week on SVD, Statistics, probability theory and linear regression. <a href="https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember9.mp4?vrtx=view-as-webpage" target="_blank">Video of Lecture</a>.</li>
<li> Friday: Linear Regression and links with Statistics, Resampling methods and presentation of first project. <a href="https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage" target="_blank">Video of Lecture</a></li>
</ul>
Recommended Reading:
<ol>
<li> Lectures on Regression</li>
<li> Bishop 1.1, 1.2, 2.1, 2.2, 2.3 and 3.1</li>
<li> Hastie et al chapter 3</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="thursday-september-9">Thursday September 9 </h2>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="summary-from-last-week-and-examples">Summary from last Week and Examples </h2>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="linear-regression-and-the-svd">Linear Regression and the SVD </h2>
<p>
We used the SVD to analyse the matrix to invert in ordinary lineat regression
$$
\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T.
$$
Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined last week the matrix
$$
\boldsymbol{\Sigma}^T\boldsymbol{\Sigma} = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\end{bmatrix},
$$
where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is
$$
\tilde{\boldsymbol{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\
0 & \sigma_1 & 0 & \dots & 0 & 0 \\
0 & 0 & \sigma_2 & \dots & 0 & 0 \\
0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\
0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\
\end{bmatrix},
$$
meaning we can write
$$
\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T.
$$
Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get
$$
\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="what-does-it-mean">What does it mean? </h2>
<p>
This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \)
are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) with eigenvalues
given by the singular values squared, that is
$$
\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2.
$$
<p>
In other words, each non-zero singular value of \( \boldsymbol{X} \) is a positive
square root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). It means also that
the columns of \( \boldsymbol{V} \) are the eigenvectors of
\( \boldsymbol{X}^T\boldsymbol{X} \). Since we have ordered the singular values of
\( \boldsymbol{X} \) in a descending order, it means that the column vectors
\( \boldsymbol{v}_i \) are hierarchically ordered by how much correlation they
encode from the columns of \( \boldsymbol{X} \).
<p>
Note that these are also the eigenvectors and eigenvalues of the
Hessian matrix.
<p>
If we now recall the definition of the covariance matrix (not using
Bessel's correction) we have
$$
\boldsymbol{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X},
$$
<p>
meaning that every squared non-singular value of \( \boldsymbol{X} \) divided by \( n \) (
the number of samples) are the eigenvalues of the covariance
matrix. Every singular value of \( \boldsymbol{X} \) is thus a positive square
root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). If the matrix \( \boldsymbol{X} \) is
self-adjoint, the singular values of \( \boldsymbol{X} \) are equal to the
absolute value of the eigenvalues of \( \boldsymbol{X} \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="and-finally-boldsymbol-x-boldsymbol-x-t">And finally \( \boldsymbol{X}\boldsymbol{X}^T \) </h2>
<p>
For \( \boldsymbol{X}\boldsymbol{X}^T \) we found
$$
\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T=\boldsymbol{U}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{U}^T.
$$
Since the matrices here have dimension \( n\times n \), we have
$$
\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \boldsymbol{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix},
$$
leading to
$$
\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}\boldsymbol{U}^T.
$$
<p>
Multiplying with \( \boldsymbol{U} \) from the right gives us the eigenvalue problem
$$
(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U}=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}.
$$
<p>
It means that the eigenvalues of \( \boldsymbol{X}\boldsymbol{X}^T \) are again given by
the non-zero singular values plus now a series of zeros. The column
vectors of \( \boldsymbol{U} \) are the eigenvectors of \( \boldsymbol{X}\boldsymbol{X}^T \) and
measure how much correlations are contained in the rows of \( \boldsymbol{X} \).
<p>
Since we will mainly be interested in the correlations among the features
of our data (the columns of \( \boldsymbol{X} \), the quantity of interest for us are the non-zero singular
values and the column vectors of \( \boldsymbol{V} \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="code-for-svd-and-inversion-of-matrices">Code for SVD and Inversion of Matrices </h2>
<p>
How do we use the SVD to invert a matrix \( \boldsymbol{X}^\boldsymbol{X} \) which is singular or near singular?
The simple answer is to use the linear algebra function for pseudoinvers, that is
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>Ainv <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linlag<span style="color: #666666">.</span>pinv(A)
</pre></div>
<p>
Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #408080; font-style: italic"># SVD inversion</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">SVDinv</span>(A):
<span style="color: #BA2121; font-style: italic">&#39;&#39;&#39; Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).</span>
<span style="color: #BA2121; font-style: italic"> SVD is numerically more stable than the inversion algorithms provided by</span>
<span style="color: #BA2121; font-style: italic"> numpy and scipy.linalg at the cost of being slower.</span>
<span style="color: #BA2121; font-style: italic"> &#39;&#39;&#39;</span>
U, s, VT <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>svd(A)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;test U&#39;</span>)
<span style="color: #008000">print</span>( (np<span style="color: #666666">.</span>transpose(U) <span style="color: #666666">@</span> U <span style="color: #666666">-</span> U <span style="color: #AA22FF">@np</span><span style="color: #666666">.</span>transpose(U)))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;test VT&#39;</span>)
<span style="color: #008000">print</span>( (np<span style="color: #666666">.</span>transpose(VT) <span style="color: #666666">@</span> VT <span style="color: #666666">-</span> VT <span style="color: #AA22FF">@np</span><span style="color: #666666">.</span>transpose(VT)))
D <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(U),<span style="color: #008000">len</span>(VT)))
D <span style="color: #666666">=</span> np<span style="color: #666666">.</span>diag(s)
UT <span style="color: #666666">=</span> np<span style="color: #666666">.</span>transpose(U); V <span style="color: #666666">=</span> np<span style="color: #666666">.</span>transpose(VT); invD <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(D)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>matmul(V,np<span style="color: #666666">.</span>matmul(invD,UT))
<span style="color: #408080; font-style: italic">#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] ])</span>
<span style="color: #408080; font-style: italic"># Non-singular square matrix</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ [<span style="color: #666666">1</span>,<span style="color: #666666">2</span>,<span style="color: #666666">3</span>],[<span style="color: #666666">2</span>,<span style="color: #666666">4</span>,<span style="color: #666666">5</span>],[<span style="color: #666666">3</span>,<span style="color: #666666">5</span>,<span style="color: #666666">6</span>]])
<span style="color: #008000">print</span>(X)
A <span style="color: #666666">=</span> np<span style="color: #666666">.</span>transpose(X) <span style="color: #666666">@</span> X
<span style="color: #408080; font-style: italic"># Brute force inversion</span>
B <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(A) <span style="color: #408080; font-style: italic"># here we could use np.linalg.pinv(A)</span>
C <span style="color: #666666">=</span> SVDinv(A)
<span style="color: #008000">print</span>(np<span style="color: #666666">.</span>abs(B<span style="color: #666666">-</span>C))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="inverse-of-rectangular-matrix">Inverse of Rectangular Matrix </h2>
<p>
Although our matrix to invert \( \boldsymbol{X}^T\boldsymbol{X} \) is a square matrix, our matrix may be singular.
<p>
The pseudoinverse is the generalization of the matrix inverse for square matrices to
rectangular matrices where the number of rows and columns are not equal.
<p>
It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.
It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.
<p>
Using the SVD we can obtain the pseudoinverse of a matrix \( \boldsymbol{A} \) (labeled here as \( \boldsymbol{A}_{\mathrm{PI}} \))
$$
\boldsymbol{A}_{\mathrm{PI}}= \boldsymbol{V}\boldsymbol{D}_{\mathrm{PI}}\boldsymbol{U}^T,
$$
where \( \boldsymbol{D}_{\mathrm{PI}} \) can be calculated by creating a diagonal matrix from \( \boldsymbol{\Sigma} \) where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #408080; font-style: italic"># SVD inversion</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">SVDinv</span>(A):
U, s, VT <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>svd(A)
<span style="color: #408080; font-style: italic"># reciprocals of singular values of s</span>
d <span style="color: #666666">=</span> <span style="color: #666666">1.0</span> <span style="color: #666666">/</span> s
<span style="color: #408080; font-style: italic"># create m x n D matrix</span>
D <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(A<span style="color: #666666">.</span>shape)
<span style="color: #408080; font-style: italic"># populate D with n x n diagonal matrix</span>
D[:A<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>], :A<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>diag(d)
UT <span style="color: #666666">=</span> np<span style="color: #666666">.</span>transpose(U)
V <span style="color: #666666">=</span> np<span style="color: #666666">.</span>transpose(VT)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>matmul(V,np<span style="color: #666666">.</span>matmul(D<span style="color: #666666">.</span>T,UT))
A <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([ [<span style="color: #666666">0.3</span>, <span style="color: #666666">0.4</span>], [<span style="color: #666666">0.5</span>, <span style="color: #666666">0.6</span>], [<span style="color: #666666">0.7</span>, <span style="color: #666666">0.8</span>],[<span style="color: #666666">0.9</span>, <span style="color: #666666">1.0</span>]])
<span style="color: #008000">print</span>(A)
<span style="color: #408080; font-style: italic"># Brute force inversion of super-collinear matrix</span>
B <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>pinv(A)
<span style="color: #008000">print</span>(B)
<span style="color: #408080; font-style: italic"># Compare our own algorithm with pinv</span>
C <span style="color: #666666">=</span> SVDinv(A)
<span style="color: #008000">print</span>(np<span style="color: #666666">.</span>abs(C<span style="color: #666666">-</span>B))
</pre></div>
<p>
As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by <b>Numpy</b>.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="ridge-and-lasso-regression">Ridge and LASSO Regression </h2>
<p>
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}.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="from-ols-to-ridge-and-lasso">From OLS to Ridge and Lasso </h2>
<p>
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
$$
<p>
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,
$$
<p>
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.
<p>
Here we have defined the norm-1 as
$$
\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="deriving-the-ridge-regression-equations">Deriving the Ridge Regression Equations </h2>
<p>
Using the matrix-vector expression for Ridge regression and dropping the parameter \( 1/n \) in front of the standard means squared error equation, we have
$$
C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
$$
and
taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then
a slightly modified matrix inversion problem which for finite values
of \( \lambda \) does not suffer from singularity problems. We obtain
the optimal parameters
$$
\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
$$
<p>
with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that
$$
\sum_{i=0}^{p-1} \beta_i^2 \leq t,
$$
<p>
with \( t \) a finite positive number.
<p>
When we compare this with the ordinary least squares result we have
$$
\hat{\boldsymbol{\beta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
$$
which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \).
<p>
We see that Ridge regression is nothing but the standard OLS with a
modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The consequences, in
particular for our discussion of the bias-variance tradeoff are rather
interesting. We will see that for specific values of \( \lambda \), we may
even reduce the variance of the optimal parameters \( \boldsymbol{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="svd-analysis">SVD analysis </h2>
<p>
Using our insights about the SVD of the design matrix \( \boldsymbol{X} \)
We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
$$
\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
$$
<p>
For Ridge regression this becomes
$$
\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{\Sigma}^2\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
$$
<p>
with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \) from the SVD of the matrix \( \boldsymbol{X} \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="interpreting-the-ridge-results">Interpreting the Ridge results </h2>
<p>
Since \( \lambda \geq 0 \), it means that compared to OLS, we have
$$
\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
$$
<p>
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} \).
<p>
For small eigenvalues \( \sigma_i \) it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-interpretations">More interpretations </h2>
<p>
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}.
$$
<p>
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},
$$
<p>
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}},
$$
<p>
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.
<p>
We will come back to more interpreations after we have gone through some of the statistical analysis part.
<p>
For more discussions of Ridge and Lasso regression, <a href="https://arxiv.org/abs/1509.09169" target="_blank">Wessel van Wieringen's</a> article is highly recommended.
Similarly, <a href="https://arxiv.org/abs/1803.08823" target="_blank">Mehta et al's article</a> is also recommended.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="deriving-the-lasso-regression-equations">Deriving the Lasso Regression Equations </h2>
<p>
Using the matrix-vector expression for Lasso regression and dropping the parameter \( 1/n \) in front of the standard mean squared error equation, we have the following <b>cost</b> function
$$
C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
$$
<p>
Taking the derivative with respect to \( \boldsymbol{\beta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
$$
\frac{d \vert \beta\vert}{d \boldsymbol{\beta}}=\mathrm{sgn}(\boldsymbol{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right.
$$
we have that the derivative of the cost function is
$$
\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-2\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0,
$$
and reordering we have
$$
\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=2\boldsymbol{X}^T\boldsymbol{y}.
$$
This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package <a href="https://cvxopt.org/" target="_blank">CVXOPT</a>. We will discuss this later.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="simple-example-to-illustrate-ordinary-least-squares-ridge-and-lasso-regression">Simple example to illustrate Ordinary Least Squares, Ridge and Lasso Regression </h2>
<p>
Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the
diagonal. In this case we have an equal number of rows and columns \( n=p \).
<p>
Our model approximation is just \( \tilde{\boldsymbol{y}}=\boldsymbol{\beta} \) and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term \( 1/n \))
$$
C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2,
$$
and minimizing we have that
$$
\hat{\beta}_i^{\mathrm{OLS}} = y_i.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="ridge-regression">Ridge Regression </h2>
<p>
For Ridge regression our cost function is
$$
C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2,
$$
and minimizing we have that
$$
\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lasso-regression">Lasso Regression </h2>
<p>
For Lasso regression our cost function is
$$
C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\vert\beta_i\vert=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\sqrt{\beta_i^2},
$$
and minimizing we have that
$$
-2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0,
$$
which leads to
$$
\hat{\boldsymbol{\beta}}_i^{\mathrm{Lasso}} = \left\{\begin{array}{ccc}y_i-\frac{\lambda}{2} &\mathrm{if} & y_i> \frac{\lambda}{2}\\
y_i+\frac{\lambda}{2} &\mathrm{if} & y_i < -\frac{\lambda}{2}\\
0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\.
$$
<p>
Plotting these results (<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf" target="_blank">figure in handwritten notes for week 36</a>) shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="yet-another-example">Yet another Example </h2>
<p>
Let us assume we have a data set with outputs/targets given by the vector
$$
\boldsymbol{y}=\begin{bmatrix}4 \\ 2 \\3\end{bmatrix},
$$
and our inputs as a \( 3\times 2 \) design matrix
$$
\boldsymbol{X}=\begin{bmatrix}2 & 0\\ 0 & 1 \\ 0 & 0\end{bmatrix},
$$
meaning that we have two features and two unknown parameters \( \beta_0 \) and \( \beta_1 \) to be determined either by ordinary least squares, Ridge or Lasso regression.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-ols-case">The OLS case </h2>
<p>
For ordinary least squares (OLS) we know that the optimal solution is
$$
\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left( \boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
Inserting the above values we obtain that
$$
\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\begin{bmatrix}2 \\ 2\end{bmatrix},
$$
<p>
The code which implements this simpler case is presented after the discussion of Ridge and Lasso.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-ridge-case">The Ridge case </h2>
<p>
For Ridge regression we have
$$
\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\left( \boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
Inserting the above values we obtain that
$$
\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\begin{bmatrix}\frac{8}{4+\lambda} \\ \frac{2}{1+\lambda}\end{bmatrix},
$$
<p>
There is normally a constraint on the value of \( \vert\vert \boldsymbol{\beta}\vert\vert_2 \) via the parameter \( \lambda \).
Let us for simplicity assume that \( \beta_0^2+\beta_1^2=1 \) as constraint. This will allow us to find an expression for the optimal values of \( \beta \) and \( \lambda \).
<p>
To see this, let us write the cost function for Ridge regression.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="writing-the-cost-function">Writing the Cost Function </h2>
<p>
We define the MSE without the \( 1/n \) factor and have then, using that
$$
\boldsymbol{X}\boldsymbol{\beta}=\begin{bmatrix} 2\beta_0 \\ \beta_1 \\0 \end{bmatrix},
$$
$$
C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\beta_0^2+\beta_1^2),
$$
and taking the derivative with respect to \( \beta_0 \) we get
$$
\beta_0=\frac{8}{4+\lambda},
$$
and for \( \beta_1 \) we obtain
$$
\beta_1=\frac{2}{1+\lambda},
$$
<p>
Using the constraint for \( \beta_0^2+\beta_1^2=1 \) we can constrain \( \lambda \) by solving
$$
\left(\frac{8}{4+\lambda}\right)^2+\left(\frac{2}{1+\lambda}\right)^2=1,
$$
which gives \( \lambda=4.571 \) and \( \beta_0=0.933 \) and \( \beta_1=0.359 \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lasso-case">Lasso case </h2>
<p>
For Lasso we need now, keeping a constraint on \( \vert\beta_0\vert+\vert\beta_1\vert=1 \), to take the derivative of the absolute values of \( \beta_0 \)
and \( \beta_1 \). This gives us the following derivatives of the cost function
$$
C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\vert\beta_0\vert+\vert\beta_1\vert),
$$
$$
\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_0}=-4(4-2\beta_0)+\lambda\mathrm{sgn}(\beta_0)=0,
$$
and
$$
\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_1}=-2(2-\beta_1)+\lambda\mathrm{sgn}(\beta_1)=0.
$$
We have now four cases to solve besides the trivial cases \( \beta_0 \) and/or \( \beta_1 \) are zero, namely
<ol>
<li> \( \beta_0 > 0 \) and \( \beta_1 > 0 \),</li>
<li> \( \beta_0 > 0 \) and \( \beta_1 < 0 \),</li>
<li> \( \beta_0 < 0 \) and \( \beta_1 > 0 \),</li>
<li> \( \beta_0 < 0 \) and \( \beta_1 < 0 \).</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-first-case">The first Case </h2>
<p>
If we consider the first case, we have then
$$
-4(4-2\beta_0)+\lambda=0,
$$
and
$$
-2(2-\beta_1)+\lambda=0.
$$
which yields
$$
\beta_0=\frac{16+\lambda}{8},
$$
and
$$
\beta_1=\frac{4+\lambda}{2}.
$$
<p>
Using the constraint on \( \beta_0 \) and \( \beta_1 \) we can then find the optimal value of \( \lambda \) for the different cases. We leave this as an exercise to you.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="simple-code-for-solving-the-above-problem">Simple code for solving the above problem </h2>
<p>
Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of \( \lambda \), meaning that we need to perform a search in order to find the optimal values.
<p>
First we study and compare the OLS and Ridge results. The next code compares all three methods.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
<span style="color: #408080; font-style: italic"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #408080; font-style: italic"># Useful for eventual debugging.</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ [ <span style="color: #666666">2</span>, <span style="color: #666666">0</span>], [<span style="color: #666666">0</span>, <span style="color: #666666">1</span>], [<span style="color: #666666">0</span>,<span style="color: #666666">0</span>]])
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [<span style="color: #666666">4</span>, <span style="color: #666666">2</span>, <span style="color: #666666">3</span>])
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
OLSbeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X) <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
<span style="color: #008000">print</span>(OLSbeta)
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ytildeOLS <span style="color: #666666">=</span> X <span style="color: #666666">@</span> OLSbeta
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Training MSE for OLS&quot;</span>)
<span style="color: #008000">print</span>(MSE(y,ytildeOLS))
ypredictOLS <span style="color: #666666">=</span> X <span style="color: #666666">@</span> OLSbeta
<span style="color: #408080; font-style: italic"># Repeat now for Ridge regression and various values of the regularization parameter</span>
I <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(<span style="color: #666666">2</span>,<span style="color: #666666">2</span>)
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">100</span>
MSEPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">4</span>, nlambdas)
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(nlambdas):
lmb <span style="color: #666666">=</span> lambdas[i]
Ridgebeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X<span style="color: #666666">+</span>lmb<span style="color: #666666">*</span>I) <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
<span style="color: #408080; font-style: italic"># print(Ridgebeta)</span>
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ypredictRidge <span style="color: #666666">=</span> X <span style="color: #666666">@</span> Ridgebeta
MSEPredict[i] <span style="color: #666666">=</span> MSE(y,ypredictRidge)
<span style="color: #408080; font-style: italic"># print(MSEPredict[i])</span>
<span style="color: #408080; font-style: italic"># Now plot the results</span>
plt<span style="color: #666666">.</span>figure()
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSEPredict, <span style="color: #BA2121">&#39;r--&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Ridge Train&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;log10(lambda)&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;MSE&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
We see here that we reach a plateau. What is actually happening?
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="with-lasso-regression">With Lasso Regression </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> linear_model
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
<span style="color: #408080; font-style: italic"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #408080; font-style: italic"># Useful for eventual debugging.</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ [ <span style="color: #666666">2</span>, <span style="color: #666666">0</span>], [<span style="color: #666666">0</span>, <span style="color: #666666">1</span>], [<span style="color: #666666">0</span>,<span style="color: #666666">0</span>]])
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [<span style="color: #666666">4</span>, <span style="color: #666666">2</span>, <span style="color: #666666">3</span>])
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
OLSbeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X) <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
<span style="color: #008000">print</span>(OLSbeta)
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ytildeOLS <span style="color: #666666">=</span> X <span style="color: #666666">@</span> OLSbeta
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Training MSE for OLS&quot;</span>)
<span style="color: #008000">print</span>(MSE(y,ytildeOLS))
ypredictOLS <span style="color: #666666">=</span> X <span style="color: #666666">@</span> OLSbeta
<span style="color: #408080; font-style: italic"># Repeat now for Ridge regression and various values of the regularization parameter</span>
I <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(<span style="color: #666666">2</span>,<span style="color: #666666">2</span>)
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">100</span>
MSERidgePredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
MSELassoPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">4</span>, nlambdas)
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(nlambdas):
lmb <span style="color: #666666">=</span> lambdas[i]
Ridgebeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X<span style="color: #666666">+</span>lmb<span style="color: #666666">*</span>I) <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
<span style="color: #008000">print</span>(Ridgebeta)
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ypredictRidge <span style="color: #666666">=</span> X <span style="color: #666666">@</span> Ridgebeta
MSERidgePredict[i] <span style="color: #666666">=</span> MSE(y,ypredictRidge)
RegLasso <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>Lasso(lmb)
RegLasso<span style="color: #666666">.</span>fit(X,y)
ypredictLasso <span style="color: #666666">=</span> RegLasso<span style="color: #666666">.</span>predict(X)
<span style="color: #008000">print</span>(RegLasso<span style="color: #666666">.</span>coef_)
MSELassoPredict[i] <span style="color: #666666">=</span> MSE(y,ypredictLasso)
<span style="color: #408080; font-style: italic"># Now plot the results</span>
plt<span style="color: #666666">.</span>figure()
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSERidgePredict, <span style="color: #BA2121">&#39;r--&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Ridge Train&#39;</span>)
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSELassoPredict, <span style="color: #BA2121">&#39;r--&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Lasso Train&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;log10(lambda)&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;MSE&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="another-example-now-with-a-polynomial-fit">Another Example, now with a polynomial fit </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> linear_model
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
<span style="color: #408080; font-style: italic"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #408080; font-style: italic"># Useful for eventual debugging.</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">3155</span>)
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">2.0+5*</span>x<span style="color: #666666">*</span>x<span style="color: #666666">+0.1*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>)
<span style="color: #408080; font-style: italic"># number of features p (here degree of polynomial</span>
p <span style="color: #666666">=</span> <span style="color: #666666">3</span>
<span style="color: #408080; font-style: italic"># The design matrix now as function of a given polynomial</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(x),p))
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
X[:,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> x
X[:,<span style="color: #666666">2</span>] <span style="color: #666666">=</span> x<span style="color: #666666">*</span>x
<span style="color: #408080; font-style: italic"># We split the data in test and training data</span>
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>)
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
OLSbeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
<span style="color: #008000">print</span>(OLSbeta)
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ytildeOLS <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> OLSbeta
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Training MSE for OLS&quot;</span>)
<span style="color: #008000">print</span>(MSE(y_train,ytildeOLS))
ypredictOLS <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> OLSbeta
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test MSE OLS&quot;</span>)
<span style="color: #008000">print</span>(MSE(y_test,ypredictOLS))
<span style="color: #408080; font-style: italic"># Repeat now for Lasso and Ridge regression and various values of the regularization parameter</span>
I <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(p,p)
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">100</span>
MSEPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
MSETrain <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
MSELassoPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
MSELassoTrain <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">4</span>, nlambdas)
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(nlambdas):
lmb <span style="color: #666666">=</span> lambdas[i]
Ridgebeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train<span style="color: #666666">+</span>lmb<span style="color: #666666">*</span>I) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
<span style="color: #408080; font-style: italic"># include lasso using Scikit-Learn</span>
RegLasso <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>Lasso(lmb)
RegLasso<span style="color: #666666">.</span>fit(X_train,y_train)
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ytildeRidge <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> Ridgebeta
ypredictRidge <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> Ridgebeta
ytildeLasso <span style="color: #666666">=</span> RegLasso<span style="color: #666666">.</span>predict(X_train)
ypredictLasso <span style="color: #666666">=</span> RegLasso<span style="color: #666666">.</span>predict(X_test)
MSEPredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictRidge)
MSETrain[i] <span style="color: #666666">=</span> MSE(y_train,ytildeRidge)
MSELassoPredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictLasso)
MSELassoTrain[i] <span style="color: #666666">=</span> MSE(y_train,ytildeLasso)
<span style="color: #408080; font-style: italic"># Now plot the results</span>
plt<span style="color: #666666">.</span>figure()
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSETrain, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Ridge train&#39;</span>)
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSEPredict, <span style="color: #BA2121">&#39;r--&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Ridge Test&#39;</span>)
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSELassoTrain, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Lasso train&#39;</span>)
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSELassoPredict, <span style="color: #BA2121">&#39;r--&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Lasso Test&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;log10(lambda)&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;MSE&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="using-cvxopt">Using CVXOPT </h2>
<p>
As a small addendum, we note that you can also solve this problem
using the convex optimization package
<a href="https://cvxopt.org/examples/mlbook/l1regls.html" target="_blank">CVXOPT</a>. This
requires, in addition to having installed <b>CVXOPT</b>, you need to
download the file <em>l1regl.py</em>. The following code example solves the
simpler problem we discussed above, where we have added the latter
python file.
<p>
We list first the needed file. Thereafter we set up the problem to solve.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">cvxopt</span> <span style="color: #008000; font-weight: bold">import</span> matrix, spdiag, mul, div, sqrt, normal, setseed
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">cvxopt</span> <span style="color: #008000; font-weight: bold">import</span> blas, lapack, solvers, sparse, spmatrix
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">math</span>
<span style="color: #008000; font-weight: bold">try</span>:
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">mosek</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">sys</span>
__MOSEK <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">True</span>
<span style="color: #008000; font-weight: bold">except</span>: __MOSEK <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">False</span>
<span style="color: #008000; font-weight: bold">if</span> __MOSEK:
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">l1regls_mosek</span>(A, b):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Returns the solution of l1-norm regularized least-squares problem</span>
<span style="color: #BA2121; font-style: italic"> minimize || A*x - b ||_2^2 + e&#39;*u</span>
<span style="color: #BA2121; font-style: italic"> subject to -u &lt;= x &lt;= u</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
m, n <span style="color: #666666">=</span> A<span style="color: #666666">.</span>size
env <span style="color: #666666">=</span> mosek<span style="color: #666666">.</span>Env()
task <span style="color: #666666">=</span> env<span style="color: #666666">.</span>Task(<span style="color: #666666">0</span>,<span style="color: #666666">0</span>)
task<span style="color: #666666">.</span>set_Stream(mosek<span style="color: #666666">.</span>streamtype<span style="color: #666666">.</span>log, <span style="color: #008000; font-weight: bold">lambda</span> x: sys<span style="color: #666666">.</span>stdout<span style="color: #666666">.</span>write(x))
task<span style="color: #666666">.</span>appendvars( <span style="color: #666666">2*</span>n) <span style="color: #408080; font-style: italic"># number of variables</span>
task<span style="color: #666666">.</span>appendcons( <span style="color: #666666">2*</span>n) <span style="color: #408080; font-style: italic"># number of constraints</span>
<span style="color: #408080; font-style: italic"># input quadratic objective</span>
Q <span style="color: #666666">=</span> matrix(<span style="color: #666666">0.0</span>, (n,n))
blas<span style="color: #666666">.</span>syrk(A, Q, alpha <span style="color: #666666">=</span> <span style="color: #666666">2.0</span>, trans<span style="color: #666666">=</span><span style="color: #BA2121">&#39;T&#39;</span>)
I <span style="color: #666666">=</span> []
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n):
I<span style="color: #666666">.</span>extend(<span style="color: #008000">range</span>(i,n))
J <span style="color: #666666">=</span> []
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n):
J<span style="color: #666666">.</span>extend((n<span style="color: #666666">-</span>i)<span style="color: #666666">*</span>[i])
task<span style="color: #666666">.</span>putqobj(I, J, <span style="color: #008000">list</span>(Q[matrix(I) <span style="color: #666666">+</span> matrix(J)<span style="color: #666666">*</span>n]))
task<span style="color: #666666">.</span>putclist(<span style="color: #008000">range</span>(<span style="color: #666666">2*</span>n), <span style="color: #008000">list</span>(<span style="color: #666666">-2*</span>A<span style="color: #666666">.</span>T<span style="color: #666666">*</span>b) <span style="color: #666666">+</span> n<span style="color: #666666">*</span>[<span style="color: #666666">1.0</span>]) <span style="color: #408080; font-style: italic"># setup linear objective</span>
<span style="color: #408080; font-style: italic"># input constraint matrix row by row</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n):
task<span style="color: #666666">.</span>putarow( i, [i, n<span style="color: #666666">+</span>i], [<span style="color: #666666">1.0</span>, <span style="color: #666666">-1.0</span>])
task<span style="color: #666666">.</span>putarow( n<span style="color: #666666">+</span>i, [i, n<span style="color: #666666">+</span>i], [<span style="color: #666666">1.0</span>, <span style="color: #666666">1.0</span>])
<span style="color: #408080; font-style: italic"># setup bounds on constraints</span>
task<span style="color: #666666">.</span>putboundslice(mosek<span style="color: #666666">.</span>accmode<span style="color: #666666">.</span>con,
<span style="color: #666666">0</span>, n, n<span style="color: #666666">*</span>[mosek<span style="color: #666666">.</span>boundkey<span style="color: #666666">.</span>up], n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>], n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>])
task<span style="color: #666666">.</span>putboundslice(mosek<span style="color: #666666">.</span>accmode<span style="color: #666666">.</span>con,
n, <span style="color: #666666">2*</span>n, n<span style="color: #666666">*</span>[mosek<span style="color: #666666">.</span>boundkey<span style="color: #666666">.</span>lo], n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>], n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>])
<span style="color: #408080; font-style: italic"># setup variable bounds</span>
task<span style="color: #666666">.</span>putboundslice(mosek<span style="color: #666666">.</span>accmode<span style="color: #666666">.</span>var,
<span style="color: #666666">0</span>, <span style="color: #666666">2*</span>n, <span style="color: #666666">2*</span>n<span style="color: #666666">*</span>[mosek<span style="color: #666666">.</span>boundkey<span style="color: #666666">.</span>fr], <span style="color: #666666">2*</span>n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>], <span style="color: #666666">2*</span>n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>])
<span style="color: #408080; font-style: italic"># optimize the task</span>
task<span style="color: #666666">.</span>putobjsense(mosek<span style="color: #666666">.</span>objsense<span style="color: #666666">.</span>minimize)
task<span style="color: #666666">.</span>optimize()
task<span style="color: #666666">.</span>solutionsummary(mosek<span style="color: #666666">.</span>streamtype<span style="color: #666666">.</span>log)
x <span style="color: #666666">=</span> n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>]
task<span style="color: #666666">.</span>getsolutionslice(mosek<span style="color: #666666">.</span>soltype<span style="color: #666666">.</span>itr, mosek<span style="color: #666666">.</span>solitem<span style="color: #666666">.</span>xx, <span style="color: #666666">0</span>, n, x)
<span style="color: #008000; font-weight: bold">return</span> matrix(x)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">l1regls_mosek2</span>(A, b):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Returns the solution of l1-norm regularized least-squares problem</span>
<span style="color: #BA2121; font-style: italic"> minimize w&#39;*w + e&#39;*u</span>
<span style="color: #BA2121; font-style: italic"> subject to -u &lt;= x &lt;= u</span>
<span style="color: #BA2121; font-style: italic"> A*x - w = b</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
m, n <span style="color: #666666">=</span> A<span style="color: #666666">.</span>size
env <span style="color: #666666">=</span> mosek<span style="color: #666666">.</span>Env()
task <span style="color: #666666">=</span> env<span style="color: #666666">.</span>Task(<span style="color: #666666">0</span>,<span style="color: #666666">0</span>)
task<span style="color: #666666">.</span>set_Stream(mosek<span style="color: #666666">.</span>streamtype<span style="color: #666666">.</span>log, <span style="color: #008000; font-weight: bold">lambda</span> x: sys<span style="color: #666666">.</span>stdout<span style="color: #666666">.</span>write(x))
task<span style="color: #666666">.</span>appendvars(<span style="color: #666666">2*</span>n <span style="color: #666666">+</span> m) <span style="color: #408080; font-style: italic"># number of variables</span>
task<span style="color: #666666">.</span>appendcons(<span style="color: #666666">2*</span>n <span style="color: #666666">+</span> m) <span style="color: #408080; font-style: italic"># number of constraints</span>
<span style="color: #408080; font-style: italic"># input quadratic objective</span>
task<span style="color: #666666">.</span>putqobj(<span style="color: #008000">range</span>(<span style="color: #666666">2*</span>n,<span style="color: #666666">2*</span>n<span style="color: #666666">+</span>m), <span style="color: #008000">range</span>(<span style="color: #666666">2*</span>n,<span style="color: #666666">2*</span>n<span style="color: #666666">+</span>m), m<span style="color: #666666">*</span>[<span style="color: #666666">2.0</span>])
task<span style="color: #666666">.</span>putclist(<span style="color: #008000">range</span>(<span style="color: #666666">2*</span>n<span style="color: #666666">+</span>m), n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>] <span style="color: #666666">+</span> n<span style="color: #666666">*</span>[<span style="color: #666666">1.0</span>] <span style="color: #666666">+</span> m<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>]) <span style="color: #408080; font-style: italic"># setup linear objective</span>
<span style="color: #408080; font-style: italic"># input constraint matrix row by row</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n):
task<span style="color: #666666">.</span>putarow( i, [i, n<span style="color: #666666">+</span>i], [<span style="color: #666666">1.0</span>, <span style="color: #666666">-1.0</span>])
task<span style="color: #666666">.</span>putarow( n<span style="color: #666666">+</span>i, [i, n<span style="color: #666666">+</span>i], [<span style="color: #666666">1.0</span>, <span style="color: #666666">1.0</span>])
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(m):
task<span style="color: #666666">.</span>putarow( <span style="color: #666666">2*</span>n<span style="color: #666666">+</span>i, <span style="color: #008000">range</span>(n) <span style="color: #666666">+</span> [<span style="color: #666666">2*</span>n<span style="color: #666666">+</span>i], <span style="color: #008000">list</span>(A[i,:]) <span style="color: #666666">+</span> [<span style="color: #666666">-1.0</span>])
<span style="color: #408080; font-style: italic"># setup bounds on constraints</span>
task<span style="color: #666666">.</span>putboundslice(mosek<span style="color: #666666">.</span>accmode<span style="color: #666666">.</span>con,
<span style="color: #666666">0</span>, n, n<span style="color: #666666">*</span>[mosek<span style="color: #666666">.</span>boundkey<span style="color: #666666">.</span>up], n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>], n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>])
task<span style="color: #666666">.</span>putboundslice(mosek<span style="color: #666666">.</span>accmode<span style="color: #666666">.</span>con,
n, <span style="color: #666666">2*</span>n, n<span style="color: #666666">*</span>[mosek<span style="color: #666666">.</span>boundkey<span style="color: #666666">.</span>lo], n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>], n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>])
task<span style="color: #666666">.</span>putboundslice(mosek<span style="color: #666666">.</span>accmode<span style="color: #666666">.</span>con,
<span style="color: #666666">2*</span>n, <span style="color: #666666">2*</span>n<span style="color: #666666">+</span>m, m<span style="color: #666666">*</span>[mosek<span style="color: #666666">.</span>boundkey<span style="color: #666666">.</span>fx], <span style="color: #008000">list</span>(b), <span style="color: #008000">list</span>(b))
<span style="color: #408080; font-style: italic"># setup variable bounds</span>
task<span style="color: #666666">.</span>putboundslice(mosek<span style="color: #666666">.</span>accmode<span style="color: #666666">.</span>var, <span style="color: #666666">0</span>, <span style="color: #666666">2*</span>n<span style="color: #666666">+</span>m, (<span style="color: #666666">2*</span>n<span style="color: #666666">+</span>m)<span style="color: #666666">*</span>[mosek<span style="color: #666666">.</span>boundkey<span style="color: #666666">.</span>fr],
(<span style="color: #666666">2*</span>n<span style="color: #666666">+</span>m)<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>], (<span style="color: #666666">2*</span>n<span style="color: #666666">+</span>m)<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>])
<span style="color: #408080; font-style: italic"># optimize the task</span>
task<span style="color: #666666">.</span>putobjsense(mosek<span style="color: #666666">.</span>objsense<span style="color: #666666">.</span>minimize)
task<span style="color: #666666">.</span>optimize()
task<span style="color: #666666">.</span>solutionsummary(mosek<span style="color: #666666">.</span>streamtype<span style="color: #666666">.</span>log)
x <span style="color: #666666">=</span> n<span style="color: #666666">*</span>[<span style="color: #666666">0.0</span>]
task<span style="color: #666666">.</span>getsolutionslice(mosek<span style="color: #666666">.</span>soltype<span style="color: #666666">.</span>itr, mosek<span style="color: #666666">.</span>solitem<span style="color: #666666">.</span>xx, <span style="color: #666666">0</span>, n, x)
<span style="color: #008000; font-weight: bold">return</span> matrix(x)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">l1regls</span>(A, b):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> </span>
<span style="color: #BA2121; font-style: italic"> Returns the solution of l1-norm regularized least-squares problem</span>
<span style="color: #BA2121; font-style: italic"> </span>
<span style="color: #BA2121; font-style: italic"> minimize || A*x - b ||_2^2 + || x ||_1.</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
m, n <span style="color: #666666">=</span> A<span style="color: #666666">.</span>size
q <span style="color: #666666">=</span> matrix(<span style="color: #666666">1.0</span>, (<span style="color: #666666">2*</span>n,<span style="color: #666666">1</span>))
q[:n] <span style="color: #666666">=</span> <span style="color: #666666">-2.0</span> <span style="color: #666666">*</span> A<span style="color: #666666">.</span>T <span style="color: #666666">*</span> b
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">P</span>(u, v, alpha <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>, beta <span style="color: #666666">=</span> <span style="color: #666666">0.0</span> ):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> v := alpha * 2.0 * [ A&#39;*A, 0; 0, 0 ] * u + beta * v </span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
v <span style="color: #666666">*=</span> beta
v[:n] <span style="color: #666666">+=</span> alpha <span style="color: #666666">*</span> <span style="color: #666666">2.0</span> <span style="color: #666666">*</span> A<span style="color: #666666">.</span>T <span style="color: #666666">*</span> (A <span style="color: #666666">*</span> u[:n])
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">G</span>(u, v, alpha<span style="color: #666666">=1.0</span>, beta<span style="color: #666666">=0.0</span>, trans<span style="color: #666666">=</span><span style="color: #BA2121">&#39;N&#39;</span>):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> v := alpha*[I, -I; -I, -I] * u + beta * v (trans = &#39;N&#39; or &#39;T&#39;)</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
v <span style="color: #666666">*=</span> beta
v[:n] <span style="color: #666666">+=</span> alpha<span style="color: #666666">*</span>(u[:n] <span style="color: #666666">-</span> u[n:])
v[n:] <span style="color: #666666">+=</span> alpha<span style="color: #666666">*</span>(<span style="color: #666666">-</span>u[:n] <span style="color: #666666">-</span> u[n:])
h <span style="color: #666666">=</span> matrix(<span style="color: #666666">0.0</span>, (<span style="color: #666666">2*</span>n,<span style="color: #666666">1</span>))
<span style="color: #408080; font-style: italic"># Customized solver for the KKT system </span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># [ 2.0*A&#39;*A 0 I -I ] [x[:n] ] [bx[:n] ]</span>
<span style="color: #408080; font-style: italic"># [ 0 0 -I -I ] [x[n:] ] = [bx[n:] ].</span>
<span style="color: #408080; font-style: italic"># [ I -I -D1^-1 0 ] [zl[:n]] [bzl[:n]]</span>
<span style="color: #408080; font-style: italic"># [ -I -I 0 -D2^-1 ] [zl[n:]] [bzl[n:]]</span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># where D1 = W[&#39;di&#39;][:n]**2, D2 = W[&#39;di&#39;][:n]**2.</span>
<span style="color: #408080; font-style: italic"># </span>
<span style="color: #408080; font-style: italic"># We first eliminate zl and x[n:]:</span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># ( 2*A&#39;*A + 4*D1*D2*(D1+D2)^-1 ) * x[:n] = </span>
<span style="color: #408080; font-style: italic"># bx[:n] - (D2-D1)*(D1+D2)^-1 * bx[n:] + </span>
<span style="color: #408080; font-style: italic"># D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - </span>
<span style="color: #408080; font-style: italic"># D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] </span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) </span>
<span style="color: #408080; font-style: italic"># - (D2-D1)*(D1+D2)^-1 * x[:n] </span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># zl[:n] = D1 * ( x[:n] - x[n:] - bzl[:n] )</span>
<span style="color: #408080; font-style: italic"># zl[n:] = D2 * (-x[:n] - x[n:] - bzl[n:] ).</span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># The first equation has the form</span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># (A&#39;*A + D)*x[:n] = rhs</span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># and is equivalent to</span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># [ D A&#39; ] [ x:n] ] = [ rhs ]</span>
<span style="color: #408080; font-style: italic"># [ A -I ] [ v ] [ 0 ].</span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># It can be solved as </span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># ( A*D^-1*A&#39; + I ) * v = A * D^-1 * rhs</span>
<span style="color: #408080; font-style: italic"># x[:n] = D^-1 * ( rhs - A&#39;*v ).</span>
S <span style="color: #666666">=</span> matrix(<span style="color: #666666">0.0</span>, (m,m))
Asc <span style="color: #666666">=</span> matrix(<span style="color: #666666">0.0</span>, (m,n))
v <span style="color: #666666">=</span> matrix(<span style="color: #666666">0.0</span>, (m,<span style="color: #666666">1</span>))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">Fkkt</span>(W):
<span style="color: #408080; font-style: italic"># Factor </span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># S = A*D^-1*A&#39; + I </span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># where D = 2*D1*D2*(D1+D2)^-1, D1 = d[:n]**-2, D2 = d[n:]**-2.</span>
d1, d2 <span style="color: #666666">=</span> W[<span style="color: #BA2121">&#39;di&#39;</span>][:n]<span style="color: #666666">**2</span>, W[<span style="color: #BA2121">&#39;di&#39;</span>][n:]<span style="color: #666666">**2</span>
<span style="color: #408080; font-style: italic"># ds is square root of diagonal of D</span>
ds <span style="color: #666666">=</span> math<span style="color: #666666">.</span>sqrt(<span style="color: #666666">2.0</span>) <span style="color: #666666">*</span> div( mul( W[<span style="color: #BA2121">&#39;di&#39;</span>][:n], W[<span style="color: #BA2121">&#39;di&#39;</span>][n:]),
sqrt(d1<span style="color: #666666">+</span>d2) )
d3 <span style="color: #666666">=</span> div(d2 <span style="color: #666666">-</span> d1, d1 <span style="color: #666666">+</span> d2)
<span style="color: #408080; font-style: italic"># Asc = A*diag(d)^-1/2</span>
Asc <span style="color: #666666">=</span> A <span style="color: #666666">*</span> spdiag(ds<span style="color: #666666">**-1</span>)
<span style="color: #408080; font-style: italic"># S = I + A * D^-1 * A&#39;</span>
blas<span style="color: #666666">.</span>syrk(Asc, S)
S[::m<span style="color: #666666">+1</span>] <span style="color: #666666">+=</span> <span style="color: #666666">1.0</span>
lapack<span style="color: #666666">.</span>potrf(S)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g</span>(x, y, z):
x[:n] <span style="color: #666666">=</span> <span style="color: #666666">0.5</span> <span style="color: #666666">*</span> ( x[:n] <span style="color: #666666">-</span> mul(d3, x[n:]) <span style="color: #666666">+</span>
mul(d1, z[:n] <span style="color: #666666">+</span> mul(d3, z[:n])) <span style="color: #666666">-</span> mul(d2, z[n:] <span style="color: #666666">-</span>
mul(d3, z[n:])) )
x[:n] <span style="color: #666666">=</span> div( x[:n], ds)
<span style="color: #408080; font-style: italic"># Solve</span>
<span style="color: #408080; font-style: italic">#</span>
<span style="color: #408080; font-style: italic"># S * v = 0.5 * A * D^-1 * ( bx[:n] - </span>
<span style="color: #408080; font-style: italic"># (D2-D1)*(D1+D2)^-1 * bx[n:] + </span>
<span style="color: #408080; font-style: italic"># D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - </span>
<span style="color: #408080; font-style: italic"># D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] )</span>
blas<span style="color: #666666">.</span>gemv(Asc, x, v)
lapack<span style="color: #666666">.</span>potrs(S, v)
<span style="color: #408080; font-style: italic"># x[:n] = D^-1 * ( rhs - A&#39;*v ).</span>
blas<span style="color: #666666">.</span>gemv(Asc, v, x, alpha<span style="color: #666666">=-1.0</span>, beta<span style="color: #666666">=1.0</span>, trans<span style="color: #666666">=</span><span style="color: #BA2121">&#39;T&#39;</span>)
x[:n] <span style="color: #666666">=</span> div(x[:n], ds)
<span style="color: #408080; font-style: italic"># x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) </span>
<span style="color: #408080; font-style: italic"># - (D2-D1)*(D1+D2)^-1 * x[:n] </span>
x[n:] <span style="color: #666666">=</span> div( x[n:] <span style="color: #666666">-</span> mul(d1, z[:n]) <span style="color: #666666">-</span> mul(d2, z[n:]), d1<span style="color: #666666">+</span>d2 )\
<span style="color: #666666">-</span> mul( d3, x[:n] )
<span style="color: #408080; font-style: italic"># zl[:n] = D1^1/2 * ( x[:n] - x[n:] - bzl[:n] )</span>
<span style="color: #408080; font-style: italic"># zl[n:] = D2^1/2 * ( -x[:n] - x[n:] - bzl[n:] ).</span>
z[:n] <span style="color: #666666">=</span> mul( W[<span style="color: #BA2121">&#39;di&#39;</span>][:n], x[:n] <span style="color: #666666">-</span> x[n:] <span style="color: #666666">-</span> z[:n] )
z[n:] <span style="color: #666666">=</span> mul( W[<span style="color: #BA2121">&#39;di&#39;</span>][n:], <span style="color: #666666">-</span>x[:n] <span style="color: #666666">-</span> x[n:] <span style="color: #666666">-</span> z[n:] )
<span style="color: #008000; font-weight: bold">return</span> g
<span style="color: #008000; font-weight: bold">return</span> solvers<span style="color: #666666">.</span>coneqp(P, q, G, h, kktsolver <span style="color: #666666">=</span> Fkkt)[<span style="color: #BA2121">&#39;x&#39;</span>][:n]
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-simpler-example">The simpler Example </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">cvxopt</span> <span style="color: #008000; font-weight: bold">import</span> matrix, normal
X <span style="color: #666666">=</span> matrix( [ [ <span style="color: #666666">2</span>, <span style="color: #666666">0</span>, <span style="color: #666666">1</span>], [<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">3</span>]])
y <span style="color: #666666">=</span> matrix( [<span style="color: #666666">4</span>, <span style="color: #666666">2</span>, <span style="color: #666666">3</span>])
x <span style="color: #666666">=</span> l1regls(X,y)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="friday-september-10">Friday September 10 </h2>
<p>
<!-- !split -->
<h2 id="linking-the-regression-analysis-with-a-statistical-interpretation">Linking the regression analysis with a statistical interpretation </h2>
<p>
We will now couple the discussions of ordinary least squares, Ridge
and Lasso regression with a statistical interpretation, that is we
move from a linear algebra analysis to a statistical analysis. In
particular, we will focus on what the regularization terms can result
in. We will amongst other things show that the regularization
parameter can reduce considerably the variance of the parameters
\( \beta \).
<p>
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.
<p>
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.
<p>
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 \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="assumptions-made">Assumptions made </h2>
<p>
The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)
that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \)
which describe our data
$$
\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
$$
<p>
We approximate this function with our model from the solution of the linear regression equations, that is our
function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with
$$
\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="expectation-value-and-variance">Expectation value and variance </h2>
<p>
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).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="expectation-value-and-variance-for-boldsymbol-beta">Expectation value and variance for \( \boldsymbol{\beta} \) </h2>
<p>
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.
<p>
We can also calculate the variance
<p>
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*}
$$
<p>
where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} +
\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2
\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the
variance of the estimate of the \( j \)-th regression coefficient:
\( \boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \). This may be used to
construct a confidence interval for the estimates.
<p>
In a similar way, we can obtain analytical expressions for say the
expectation values of the parameters \( \boldsymbol{\beta} \) and their variance
when we employ Ridge regression, allowing us again to define a confidence interval.
<p>
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.
<p>
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.
<p>
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.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="deriving-ols-from-a-probability-distribution">Deriving OLS from a probability distribution </h2>
<p>
Our basic assumption when we derived the OLS equations was to assume
that our output is determined by a given continuous function
\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal
distribution with zero mean value and an undetermined variance
\( \sigma^2 \).
<p>
We found above that the outputs \( \boldsymbol{y} \) have a mean value given by
\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to
the design matrix are not stochastic variables, we can assume that the
probability distribution of our targets is also a normal distribution
but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a
single output \( y_i \) is given by the Gaussian distribution
$$
y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="independent-and-identically-distrubuted-iid">Independent and Identically Distrubuted (iid) </h2>
<p>
We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution.
We define this distribution as
$$
p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]},
$$
which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \).
<p>
Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have
$$
p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}).
$$
<p>
We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is
in case we have a simple one-dimensional input and output case
$$
\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
$$
In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \).
We can now rewrite the above probability as
$$
p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
$$
<p>
It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="maximum-likelihood-estimation-mle">Maximum Likelihood Estimation (MLE) </h2>
<p>
In statistics, maximum likelihood estimation (MLE) is a method of
estimating the parameters of an assumed probability distribution,
given some observed data. This is achieved by maximizing a likelihood
function so that, under the assumed statistical model, the observed
data is the most probable.
<p>
We will assume here that our events are given by the above Gaussian
distribution and we will determine the optimal parameters \( \beta \) by
maximizing the above PDF. However, computing the derivatives of a
product function is cumbersome and can easily lead to overflow and/or
underflowproblems, with potentials for loss of numerical precision.
<p>
In practice, it is more convenient to maximize the logarithm of the
PDF because it is a monotonically increasing function of the argument.
Alternatively, and this will be our option, we will minimize the
negative of the logarithm since this is a monotonically decreasing
function.
<p>
Note also that maximization/minimization of the logarithm of the PDF
is equivalent to the maximization/minimization of the function itself.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-new-cost-function">A new Cost Function </h2>
<p>
We could now define a new cost function to minimize, namely the negative logarithm of the above PDF
$$
C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})},
$$
which becomes
$$
C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}.
$$
<p>
Taking the derivative of the <em>new</em> cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely
$$
\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0,
$$
which leads to the well-known OLS equation for the optimal paramters \( \beta \)
$$
\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}!
$$
<p>
Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-basic-statistics-and-bayes-theorem">More basic Statistics and Bayes' theorem </h2>
<p>
A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.
Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.
<p>
Assume we have two domains of events \( X=[x_0,x_1,\dots,x_{n-1}] \) and \( Y=[y_0,y_1,\dots,y_{n-1}] \).
<p>
We define also the likelihood for \( X \) and \( Y \) as \( p(X) \) and \( p(Y) \) respectively.
The likelihood of a specific event \( x_i \) (or \( y_i \)) is then written as \( p(X=x_i) \) or just \( p(x_i)=p_i \).
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b>Union of events is given by</b>
<p>
$$
p(X \cup Y)= p(X)+p(Y)-p(X \cap Y).
$$
</div>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b>The product rule (aka joint probability) is given by</b>
<p>
$$
p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X),
$$
where we read \( p(X\vert Y) \) as the likelihood of obtaining \( X \) given \( Y \).
</div>
<p>
If we have independent events then \( p(X,Y)=p(X)p(Y) \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="marginal-probability">Marginal Probability </h2>
<p>
The marginal probability is defined in terms of only one of the set of variables \( X,Y \). For a discrete probability we have
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
$$
p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i).
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="conditional-probability">Conditional Probability </h2>
<p>
The conditional probability, if \( p(Y) > 0 \), is
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
$$
p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}.
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="bayes-theorem">Bayes' Theorem </h2>
<p>
If we combine the conditional probability with the marginal probability and the standard product rule, we have
$$
p(X\vert Y)= \frac{p(X,Y)}{p(Y)},
$$
which we can rewrite as
$$
p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)},
$$
which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="interpretations-of-bayes-theorem">Interpretations of Bayes' Theorem </h2>
<p>
The quantity \( p(Y\vert X) \) on the right-hand side of the theorem is
evaluated for the observed data \( Y \) and can be viewed as a function of
the parameter space represented by \( X \). This function is not
necesseraly normalized and is normally called the likelihood function.
<p>
The function \( p(X) \) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.
<p>
Let us try to illustrate Bayes' theorem through an example.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="example-of-usage-of-bayes-theorem">Example of Usage of Bayes' theorem </h2>
<p>
Let us suppose that you are undergoing a series of mammography scans in
order to rule out possible breast cancer cases. We define the
sensitivity for a positive event by the variable \( X \). It takes binary
values with \( X=1 \) representing a positive event and \( X=0 \) being a
negative event. We reserve \( Y \) as a classification parameter for
either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).
<p>
We let \( Y=1 \) represent the the case of having breast cancer and \( Y=0 \) as not.
<p>
Let us assume that if you have breast cancer, the test will be positive with a probability of \( 0.8 \), that is we have
$$
p(X=1\vert Y=1) =0.8.
$$
<p>
This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of \( 80\% \) for having cancer.
It is however not correct, as the following Bayesian analysis shows.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="doing-it-correctly">Doing it correctly </h2>
<p>
If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.
Let us assume that the prior probability in the population as a whole is
$$
p(Y=1) =0.004.
$$
<p>
We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have
$$
p(X=1\vert Y=0) =0.1.
$$
<p>
Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute
$$
p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031.
$$
That is, in case of a positive test, there is only a \( 3\% \) chance of having breast cancer!
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="bayes-theorem-and-ridge-and-lasso-regression">Bayes' Theorem and Ridge and Lasso Regression </h2>
<p>
Hitherto we have discussed Ridge and Lasso regression in terms of a
linear analysis. This may to many of you feel rather technical and
perhaps not that intuitive. The question is whether we can develop a
more intuitive way of understanding what Ridge and Lasso express.
<p>
Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="test-function-for-what-happens-with-ols-ridge-and-lasso">Test Function for what happens with OLS, Ridge and Lasso </h2>
<p>
We will play around with a study of the values for the optimal
parameters \( \boldsymbol{\beta} \) using OLS, Ridge and Lasso regression. For
OLS, you will notice as function of the noise and polynomial degree,
that the parameters \( \beta \) will fluctuate from order to order in the
polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.
<p>
For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> linear_model
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
<span style="color: #408080; font-style: italic"># Make data set.</span>
n <span style="color: #666666">=</span> <span style="color: #666666">10000</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(n)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>x<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> <span style="color: #666666">1.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(n)
Maxpolydegree <span style="color: #666666">=</span> <span style="color: #666666">5</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(x),Maxpolydegree))
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
<span style="color: #008000; font-weight: bold">for</span> polydegree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>, Maxpolydegree):
<span style="color: #008000; font-weight: bold">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(polydegree):
X[:,degree] <span style="color: #666666">=</span> x<span style="color: #666666">**</span>(degree)
<span style="color: #408080; font-style: italic"># We split the data in test and training data</span>
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>)
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
OLSbeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>pinv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
<span style="color: #008000">print</span>(OLSbeta)
ypredictOLS <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> OLSbeta
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test MSE OLS&quot;</span>)
<span style="color: #008000">print</span>(MSE(y_test,ypredictOLS))
<span style="color: #408080; font-style: italic"># Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn</span>
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">4</span>
MSERidgePredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
MSELassoPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-3</span>, <span style="color: #666666">1</span>, nlambdas)
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(nlambdas):
lmb <span style="color: #666666">=</span> lambdas[i]
<span style="color: #408080; font-style: italic"># Make the fit using Ridge and Lasso</span>
RegRidge <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>Ridge(lmb,fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
RegRidge<span style="color: #666666">.</span>fit(X_train,y_train)
RegLasso <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>Lasso(lmb,fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
RegLasso<span style="color: #666666">.</span>fit(X_train,y_train)
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ypredictRidge <span style="color: #666666">=</span> RegRidge<span style="color: #666666">.</span>predict(X_test)
ypredictLasso <span style="color: #666666">=</span> RegLasso<span style="color: #666666">.</span>predict(X_test)
<span style="color: #408080; font-style: italic"># Compute the MSE and print it</span>
MSERidgePredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictRidge)
MSELassoPredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictLasso)
<span style="color: #008000">print</span>(lmb,RegRidge<span style="color: #666666">.</span>coef_)
<span style="color: #008000">print</span>(lmb,RegLasso<span style="color: #666666">.</span>coef_)
<span style="color: #408080; font-style: italic"># Now plot the results</span>
plt<span style="color: #666666">.</span>figure()
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSERidgePredict, <span style="color: #BA2121">&#39;b&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Ridge Test&#39;</span>)
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSELassoPredict, <span style="color: #BA2121">&#39;r&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Lasso Test&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;log10(lambda)&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;MSE&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
How can we understand this?
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="invoking-bayes-theorem">Invoking Bayes' theorem </h2>
<p>
Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression.
<p>
For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case)
$$
\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})],
$$
is given by
$$
p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
$$
<p>
In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \( \boldsymbol{\beta} \) given a domain of events \( \boldsymbol{D} \)? That is, how can we define the posterior probability
$$
p(\boldsymbol{\beta}\vert\boldsymbol{D}).
$$
<p>
Bayes' theorem comes to our rescue here since (omitting the normalization constant)
$$
p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}).
$$
<p>
We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one for the <b>prior</b> \( p(\boldsymbol{\beta} \)!
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="ridge-and-bayes">Ridge and Bayes </h2>
<p>
With the posterior probability defined by a likelihood which we have
already modeled and an unknown prior, we are now ready to make
additional models for the prior.
<p>
We can, based on our discussions of the variance of \( \boldsymbol{\beta} \) and the mean value, assume that the prior for the values \( \boldsymbol{\beta} \) is given by a Gaussian with mean value zero and variance \( \tau^2 \), that is
$$
p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
$$
<p>
Our posterior probability becomes then (omitting the normalization factor which is just a constant)
$$
p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
$$
<p>
We can now optimize this quantity with respect to \( \boldsymbol{\beta} \). As we
did for OLS, this is most conveniently done by taking the negative
logarithm of the posterior probability. Doing so and leaving out the
constants terms that do not depend on \( \beta \), we have
$$
C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
$$
and replacing \( 1/2\tau^2 \) with \( \lambda \) we have
$$
C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
$$
which is our Ridge cost function! Nice, isn't it?
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lasso-and-bayes">Lasso and Bayes </h2>
<p>
To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (<a href="https://en.wikipedia.org/wiki/Laplace_distribution" target="_blank">Laplace in this case</a>) with zero mean value, that is
$$
p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
$$
<p>
Our posterior probability becomes then (omitting the normalization factor which is just a constant)
$$
p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
$$
<p>
Taking the negative
logarithm of the posterior probability and leaving out the
constants terms that do not depend on \( \beta \), we have
$$
C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1,
$$
and replacing \( 1/\tau \) with \( \lambda \) we have
$$
C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
$$
which is our Lasso cost function!
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>