Files
FYS-STK4155/doc/pub/week36/html/week36-solarized.html
T
Morten Hjorth-Jensen e1dfee4ce4 added whiteboard notes
2023-09-07 15:30:31 +02:00

2377 lines
118 KiB
HTML

<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week36.do.txt --pygments_html_style=perldoc --html_style=solarized3 --html_links_in_new_window --html_output=week36-solarized --no_mako
-->
<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>
<link href="https://cdn.rawgit.com/doconce/doconce/master/bundled/html_styles/style_solarized_box/css/solarized_light_code.css" rel="stylesheet" type="text/css" title="light"/>
<script src="https://cdn.rawgit.com/doconce/doconce/master/bundled/html_styles/style_solarized_box/js/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link href="https://thomasf.github.io/solarized-css/solarized-light.min.css" rel="stylesheet">
<style type="text/css">
h1 {color: #b58900;} /* yellow */
/* h1 {color: #cb4b16;} orange */
/* h1 {color: #d33682;} magenta, the original choice of thomasf */
code { padding: 0px; background-color: inherit; }
pre {
border: 0pt solid #93a1a1;
box-shadow: none;
}
.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 #93a1a1;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
color: #555;
background-color: #eee8d5;
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_yellow_notice.png); }
.alert-summary { background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_yellow_summary.png); }
.alert-warning { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_yellow_warning.png); }
.alert-question {background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_yellow_question.png); }
div { text-align: justify; text-justify: inter-word; }
.tab {
padding-left: 1.5em;
}
div.toc p,a {
line-height: 1.3;
margin-top: 1.1;
margin-bottom: 1.1;
}
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 36', 2, None, 'plans-for-week-36'),
('Material for the active learning sessions Tuesday and '
'Wednesday',
2,
None,
'material-for-the-active-learning-sessions-tuesday-and-wednesday'),
('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'),
('Note on Scikit-Learn', 2, None, 'note-on-scikit-learn'),
('Comparison with OLS', 2, None, 'comparison-with-ols'),
('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'),
('Material for lecture Thursday September 7',
2,
None,
'material-for-lecture-thursday-september-7'),
('Important technicalities: More on Rescaling data',
2,
None,
'important-technicalities-more-on-rescaling-data'),
('Test Function for what happens with OLS, Ridge and Lasso',
2,
None,
'test-function-for-what-happens-with-ols-ridge-and-lasso'),
('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'),
('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 -->
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<!-- 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>
<center>
<h4>September 4-8, 2023</h4>
</center> <!-- date -->
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plans-for-week-36">Plans for week 36 </h2>
<ul>
<li> Material for the active learning sessions on Tuesday and Wednesday</li>
<ul>
<li> Summary from last week on discussion of SVD, Ridge and Lasso linear regression.</li>
<li> Recommended Reading: Hastie et al chapter 3, see <a href="https://link.springer.com/book/10.1007/978-0-387-84858-7" target="_blank"><tt>https://link.springer.com/book/10.1007/978-0-387-84858-7</tt></a></li>
<li> Presentation and discussion of first project</li>
</ul>
<li> Material for the lecture on Thursday September 7</li>
<ul>
<li> Technicalities related to scaling and other issues with data handling</li>
<li> Linear Regression and links with Statistics</li>
<li> <a href="https://www.deeplearningbook.org/" target="_blank">Recommended Reading: Goodfellow et al chapter 3 on probability theory</a></li>
<li> See also Murphy, sections 2.4 (Gaussian distributions) and 3.2 (Bayesian Statistics, basis)</li>
<li> <a href="https://youtu.be/Kc20CFK0z7Y" target="_blank">Video of lecture</a></li>
<li> <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesSep7.pdf" target="_blank">Whiteboard notes</a></li>
</ul>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="material-for-the-active-learning-sessions-tuesday-and-wednesday">Material for the active learning sessions Tuesday and Wednesday </h2>
<p>The material here contains a summary from last week and discussion of SVD, Ridge and Lasso regression with examples </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</p>
$$
\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.
$$
<p>Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined last week the matrix</p>
$$
\boldsymbol{\Sigma}^T\boldsymbol{\Sigma} = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\end{bmatrix},
$$
<p>where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is</p>
$$
\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},
$$
<p>meaning we can write</p>
$$
\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T.
$$
<p>Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get</p>
$$
\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2.
$$
<!-- !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
</p>
$$
\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>
<p>Note that these are also the eigenvectors and eigenvalues of the
Hessian matrix.
</p>
<p>If we now recall the definition of the covariance matrix (not using
Bessel's correction) we have
</p>
$$
\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</p>
$$
\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.
$$
<p>Since the matrices here have dimension \( n\times n \), we have</p>
$$
\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},
$$
<p>leading to</p>
$$
\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</p>
$$
(\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>
<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 the computation of the pseudoinverse of a given matrix \( \boldsymbol{X} \), that is
</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
X = np.array( [ [<span style="color: #B452CD">1</span>,<span style="color: #B452CD">2</span>,<span style="color: #B452CD">3</span>],[<span style="color: #B452CD">2</span>,<span style="color: #B452CD">4</span>,<span style="color: #B452CD">5</span>],[<span style="color: #B452CD">3</span>,<span style="color: #B452CD">5</span>,<span style="color: #B452CD">6</span>]])
Xinv = np.linlag.pinv(X)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</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 "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #228B22"># SVD inversion</span>
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">SVDinv</span>(A):
<span style="color: #CD5555">&#39;&#39;&#39; Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).</span>
<span style="color: #CD5555"> SVD is numerically more stable than the inversion algorithms provided by</span>
<span style="color: #CD5555"> numpy and scipy.linalg at the cost of being slower.</span>
<span style="color: #CD5555"> &#39;&#39;&#39;</span>
U, s, VT = np.linalg.svd(A)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;test U&#39;</span>)
<span style="color: #658b00">print</span>( (np.transpose(U) @ U - U <span style="color: #707a7c">@np</span>.transpose(U)))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;test VT&#39;</span>)
<span style="color: #658b00">print</span>( (np.transpose(VT) @ VT - VT <span style="color: #707a7c">@np</span>.transpose(VT)))
D = np.zeros((<span style="color: #658b00">len</span>(U),<span style="color: #658b00">len</span>(VT)))
D = np.diag(s)
UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
<span style="color: #8B008B; font-weight: bold">return</span> np.matmul(V,np.matmul(invD,UT))
<span style="color: #228B22">#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: #228B22"># Non-singular square matrix</span>
X = np.array( [ [<span style="color: #B452CD">1</span>,<span style="color: #B452CD">2</span>,<span style="color: #B452CD">3</span>],[<span style="color: #B452CD">2</span>,<span style="color: #B452CD">4</span>,<span style="color: #B452CD">5</span>],[<span style="color: #B452CD">3</span>,<span style="color: #B452CD">5</span>,<span style="color: #B452CD">6</span>]])
<span style="color: #658b00">print</span>(X)
A = np.transpose(X) @ X
<span style="color: #228B22"># Brute force inversion</span>
B = np.linalg.inv(A) <span style="color: #228B22"># here we could use np.linalg.pinv(A)</span>
C = SVDinv(A)
<span style="color: #658b00">print</span>(np.abs(B-C))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !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>
<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>
<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>
<p>Using the SVD we can obtain the pseudoinverse of a matrix \( \boldsymbol{A} \) (labeled here as \( \boldsymbol{A}_{\mathrm{PI}} \))</p>
$$
\boldsymbol{A}_{\mathrm{PI}}= \boldsymbol{V}\boldsymbol{D}_{\mathrm{PI}}\boldsymbol{U}^T,
$$
<p>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 "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #228B22"># SVD inversion</span>
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">SVDinv</span>(A):
U, s, VT = np.linalg.svd(A)
<span style="color: #228B22"># reciprocals of singular values of s</span>
d = <span style="color: #B452CD">1.0</span> / s
<span style="color: #228B22"># create m x n D matrix</span>
D = np.zeros(A.shape)
<span style="color: #228B22"># populate D with n x n diagonal matrix</span>
D[:A.shape[<span style="color: #B452CD">1</span>], :A.shape[<span style="color: #B452CD">1</span>]] = np.diag(d)
UT = np.transpose(U)
V = np.transpose(VT)
<span style="color: #8B008B; font-weight: bold">return</span> np.matmul(V,np.matmul(D.T,UT))
A = np.array([ [<span style="color: #B452CD">0.3</span>, <span style="color: #B452CD">0.4</span>], [<span style="color: #B452CD">0.5</span>, <span style="color: #B452CD">0.6</span>], [<span style="color: #B452CD">0.7</span>, <span style="color: #B452CD">0.8</span>],[<span style="color: #B452CD">0.9</span>, <span style="color: #B452CD">1.0</span>]])
<span style="color: #658b00">print</span>(A)
<span style="color: #228B22"># Brute force inversion of super-collinear matrix</span>
B = np.linalg.pinv(A)
<span style="color: #658b00">print</span>(B)
<span style="color: #228B22"># Compare our own algorithm with pinv</span>
C = SVDinv(A)
<span style="color: #658b00">print</span>(np.abs(C-B))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>As you can see from this example, our own decomposition based on the SVD agrees with 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
</p>
$$
{\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\}.
$$
<p>or we can state it as</p>
$$
{\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,
$$
<p>where we have used the definition of a norm-2 vector, that is</p>
$$
\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
$$
<!-- !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
</p>
$$
{\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. We do not include such a constraints in the discussions here.
</p>
<p>By defining</p>
$$
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</p>
$$
{\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
$$
<p>which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. </p>
<p>Here we have defined the norm-1 as </p>
$$
\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
$$
<!-- !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</p>
$$
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},
$$
<p>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
</p>
$$
\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</p>
$$
\sum_{i=0}^{p-1} \beta_i^2 \leq t,
$$
<p>with \( t \) a finite positive number. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="note-on-scikit-learn">Note on Scikit-Learn </h2>
<p>Note well that a library like <b>Scikit-Learn</b> does not include the \( 1/n \) factor in the expression for the mean-squared error. If you include it, the optimal parameter \( \beta \) becomes</p>
$$
\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+n\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
<p>In our codes where we compare our own codes with <b>Scikit-Learn</b>, we do thus not include the \( 1/n \) factor in the cost function.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="comparison-with-ols">Comparison with OLS </h2>
<p>When we compare this with the ordinary least squares result we have</p>
$$
\hat{\boldsymbol{\beta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
$$
<p>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>
<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
</p>
$$
\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
$$
<p>For Ridge regression this becomes</p>
$$
\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 </p>
$$
\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>
<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 </p>
$$
\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
$$
<p>In this case the standard OLS results in </p>
$$
\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y},
$$
<p>and</p>
$$
\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>
<p>We will come back to more interpreations after we have gone through some of the statistical analysis part. </p>
<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, we have the following <b>cost</b> function</p>
$$
C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\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 simplicity)</p>
$$
\frac{d \vert \beta\vert}{d \beta}=\mathrm{sgn}(\beta)=\left\{\begin{array}{cc} 1 & \beta > 0 \\-1 & \beta < 0, \end{array}\right.
$$
<p>we have that the derivative of the cost function is</p>
$$
\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-\frac{2}{n}\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0,
$$
<p>and reordering we have</p>
$$
\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=\boldsymbol{X}^T\boldsymbol{y}.
$$
<p>This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. We have absorbed the factor \( 2/n \) in a redefinition of the parameter \( \lambda \). We will solve this type of problems using libraries like <b>scikit-learn</b>.</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>
<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 \)) </p>
$$
C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2,
$$
<p>and minimizing we have that</p>
$$
\hat{\beta}_i^{\mathrm{OLS}} = y_i.
$$
<!-- !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</p>
$$
C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2,
$$
<p>and minimizing we have that</p>
$$
\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}.
$$
<!-- !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</p>
$$
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},
$$
<p>and minimizing we have that</p>
$$
-2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0,
$$
<p>which leads to </p>
$$
\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 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</p>
$$
\boldsymbol{y}=\begin{bmatrix}4 \\ 2 \\3\end{bmatrix},
$$
<p>and our inputs as a \( 3\times 2 \) design matrix</p>
$$
\boldsymbol{X}=\begin{bmatrix}2 & 0\\ 0 & 1 \\ 0 & 0\end{bmatrix},
$$
<p>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</p>
$$
\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left( \boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
<p>Inserting the above values we obtain that </p>
$$
\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</p>
$$
\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\left( \boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
<p>Inserting the above values we obtain that </p>
$$
\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>
<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</p>
$$
\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),
$$
<p>and taking the derivative with respect to \( \beta_0 \) we get</p>
$$
\beta_0=\frac{8}{4+\lambda},
$$
<p>and for \( \beta_1 \) we obtain</p>
$$
\beta_1=\frac{2}{1+\lambda},
$$
<p>Using the constraint for \( \beta_0^2+\beta_1^2=1 \) we can constrain \( \lambda \) by solving</p>
$$
\left(\frac{8}{4+\lambda}\right)^2+\left(\frac{2}{1+\lambda}\right)^2=1,
$$
<p>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
</p>
$$
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,
$$
<p>and</p>
$$
\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_1}=-2(2-\beta_1)+\lambda\mathrm{sgn}(\beta_1)=0.
$$
<p>We have now four cases to solve besides the trivial cases \( \beta_0 \) and/or \( \beta_1 \) are zero, namely</p>
<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</p>
$$
-4(4-2\beta_0)+\lambda=0,
$$
<p>and</p>
$$
-2(2-\beta_1)+\lambda=0.
$$
<p>which yields</p>
$$
\beta_0=\frac{16+\lambda}{8},
$$
<p>and</p>
$$
\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>
<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 "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">os</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">R2</span>(y_data, y_model):
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">1</span> - np.sum((y_data - y_model) ** <span style="color: #B452CD">2</span>) / np.sum((y_data - np.mean(y_data)) ** <span style="color: #B452CD">2</span>)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">MSE</span>(y_data,y_model):
n = np.size(y_model)
<span style="color: #8B008B; font-weight: bold">return</span> np.sum((y_data-y_model)**<span style="color: #B452CD">2</span>)/n
<span style="color: #228B22"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #228B22"># Useful for eventual debugging.</span>
X = np.array( [ [ <span style="color: #B452CD">2</span>, <span style="color: #B452CD">0</span>], [<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>], [<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>]])
y = np.array( [<span style="color: #B452CD">4</span>, <span style="color: #B452CD">2</span>, <span style="color: #B452CD">3</span>])
<span style="color: #228B22"># matrix inversion to find beta</span>
OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y
<span style="color: #658b00">print</span>(OLSbeta)
<span style="color: #228B22"># and then make the prediction</span>
ytildeOLS = X @ OLSbeta
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Training MSE for OLS&quot;</span>)
<span style="color: #658b00">print</span>(MSE(y,ytildeOLS))
ypredictOLS = X @ OLSbeta
<span style="color: #228B22"># Repeat now for Ridge regression and various values of the regularization parameter</span>
I = np.eye(<span style="color: #B452CD">2</span>,<span style="color: #B452CD">2</span>)
<span style="color: #228B22"># Decide which values of lambda to use</span>
nlambdas = <span style="color: #B452CD">100</span>
MSEPredict = np.zeros(nlambdas)
lambdas = np.logspace(-<span style="color: #B452CD">4</span>, <span style="color: #B452CD">4</span>, nlambdas)
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(nlambdas):
lmb = lambdas[i]
Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
<span style="color: #228B22"># print(Ridgebeta)</span>
<span style="color: #228B22"># and then make the prediction</span>
ypredictRidge = X @ Ridgebeta
MSEPredict[i] = MSE(y,ypredictRidge)
<span style="color: #228B22"># print(MSEPredict[i])</span>
<span style="color: #228B22"># Now plot the results</span>
plt.figure()
plt.plot(np.log10(lambdas), MSEPredict, <span style="color: #CD5555">&#39;r--&#39;</span>, label = <span style="color: #CD5555">&#39;MSE Ridge Train&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;log10(lambda)&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;MSE&#39;</span>)
plt.legend()
plt.show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</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>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">os</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn</span> <span style="color: #8B008B; font-weight: bold">import</span> linear_model
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">R2</span>(y_data, y_model):
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">1</span> - np.sum((y_data - y_model) ** <span style="color: #B452CD">2</span>) / np.sum((y_data - np.mean(y_data)) ** <span style="color: #B452CD">2</span>)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">MSE</span>(y_data,y_model):
n = np.size(y_model)
<span style="color: #8B008B; font-weight: bold">return</span> np.sum((y_data-y_model)**<span style="color: #B452CD">2</span>)/n
<span style="color: #228B22"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #228B22"># Useful for eventual debugging.</span>
X = np.array( [ [ <span style="color: #B452CD">2</span>, <span style="color: #B452CD">0</span>], [<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>], [<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>]])
y = np.array( [<span style="color: #B452CD">4</span>, <span style="color: #B452CD">2</span>, <span style="color: #B452CD">3</span>])
<span style="color: #228B22"># matrix inversion to find beta</span>
OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y
<span style="color: #658b00">print</span>(OLSbeta)
<span style="color: #228B22"># and then make the prediction</span>
ytildeOLS = X @ OLSbeta
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Training MSE for OLS&quot;</span>)
<span style="color: #658b00">print</span>(MSE(y,ytildeOLS))
ypredictOLS = X @ OLSbeta
<span style="color: #228B22"># Repeat now for Ridge regression and various values of the regularization parameter</span>
I = np.eye(<span style="color: #B452CD">2</span>,<span style="color: #B452CD">2</span>)
<span style="color: #228B22"># Decide which values of lambda to use</span>
nlambdas = <span style="color: #B452CD">100</span>
MSERidgePredict = np.zeros(nlambdas)
MSELassoPredict = np.zeros(nlambdas)
lambdas = np.logspace(-<span style="color: #B452CD">4</span>, <span style="color: #B452CD">4</span>, nlambdas)
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(nlambdas):
lmb = lambdas[i]
Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
<span style="color: #658b00">print</span>(Ridgebeta)
<span style="color: #228B22"># and then make the prediction</span>
ypredictRidge = X @ Ridgebeta
MSERidgePredict[i] = MSE(y,ypredictRidge)
RegLasso = linear_model.Lasso(lmb,fit_intercept=<span style="color: #8B008B; font-weight: bold">False</span>)
RegLasso.fit(X,y)
ypredictLasso = RegLasso.predict(X)
<span style="color: #658b00">print</span>(RegLasso.coef_)
MSELassoPredict[i] = MSE(y,ypredictLasso)
<span style="color: #228B22"># Now plot the results</span>
plt.figure()
plt.plot(np.log10(lambdas), MSERidgePredict, <span style="color: #CD5555">&#39;r--&#39;</span>, label = <span style="color: #CD5555">&#39;MSE Ridge Train&#39;</span>)
plt.plot(np.log10(lambdas), MSELassoPredict, <span style="color: #CD5555">&#39;r--&#39;</span>, label = <span style="color: #CD5555">&#39;MSE Lasso Train&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;log10(lambda)&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;MSE&#39;</span>)
plt.legend()
plt.show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !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>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">os</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn</span> <span style="color: #8B008B; font-weight: bold">import</span> linear_model
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">R2</span>(y_data, y_model):
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">1</span> - np.sum((y_data - y_model) ** <span style="color: #B452CD">2</span>) / np.sum((y_data - np.mean(y_data)) ** <span style="color: #B452CD">2</span>)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">MSE</span>(y_data,y_model):
n = np.size(y_model)
<span style="color: #8B008B; font-weight: bold">return</span> np.sum((y_data-y_model)**<span style="color: #B452CD">2</span>)/n
<span style="color: #228B22"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #228B22"># Useful for eventual debugging.</span>
np.random.seed(<span style="color: #B452CD">3155</span>)
x = np.random.rand(<span style="color: #B452CD">100</span>)
y = <span style="color: #B452CD">2.0</span>+<span style="color: #B452CD">5</span>*x*x+<span style="color: #B452CD">0.1</span>*np.random.randn(<span style="color: #B452CD">100</span>)
<span style="color: #228B22"># number of features p (here degree of polynomial</span>
p = <span style="color: #B452CD">3</span>
<span style="color: #228B22"># The design matrix now as function of a given polynomial</span>
X = np.zeros((<span style="color: #658b00">len</span>(x),p))
X[:,<span style="color: #B452CD">0</span>] = <span style="color: #B452CD">1.0</span>
X[:,<span style="color: #B452CD">1</span>] = x
X[:,<span style="color: #B452CD">2</span>] = x*x
<span style="color: #228B22"># We split the data in test and training data</span>
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=<span style="color: #B452CD">0.2</span>)
<span style="color: #228B22"># matrix inversion to find beta</span>
OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
<span style="color: #658b00">print</span>(OLSbeta)
<span style="color: #228B22"># and then make the prediction</span>
ytildeOLS = X_train @ OLSbeta
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Training MSE for OLS&quot;</span>)
<span style="color: #658b00">print</span>(MSE(y_train,ytildeOLS))
ypredictOLS = X_test @ OLSbeta
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test MSE OLS&quot;</span>)
<span style="color: #658b00">print</span>(MSE(y_test,ypredictOLS))
<span style="color: #228B22"># Repeat now for Lasso and Ridge regression and various values of the regularization parameter</span>
I = np.eye(p,p)
<span style="color: #228B22"># Decide which values of lambda to use</span>
nlambdas = <span style="color: #B452CD">100</span>
MSEPredict = np.zeros(nlambdas)
MSETrain = np.zeros(nlambdas)
MSELassoPredict = np.zeros(nlambdas)
MSELassoTrain = np.zeros(nlambdas)
lambdas = np.logspace(-<span style="color: #B452CD">4</span>, <span style="color: #B452CD">4</span>, nlambdas)
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(nlambdas):
lmb = lambdas[i]
Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
<span style="color: #228B22"># include lasso using Scikit-Learn</span>
RegLasso = linear_model.Lasso(lmb,fit_intercept=<span style="color: #8B008B; font-weight: bold">False</span>)
RegLasso.fit(X_train,y_train)
<span style="color: #228B22"># and then make the prediction</span>
ytildeRidge = X_train @ Ridgebeta
ypredictRidge = X_test @ Ridgebeta
ytildeLasso = RegLasso.predict(X_train)
ypredictLasso = RegLasso.predict(X_test)
MSEPredict[i] = MSE(y_test,ypredictRidge)
MSETrain[i] = MSE(y_train,ytildeRidge)
MSELassoPredict[i] = MSE(y_test,ypredictLasso)
MSELassoTrain[i] = MSE(y_train,ytildeLasso)
<span style="color: #228B22"># Now plot the results</span>
plt.figure()
plt.plot(np.log10(lambdas), MSETrain, label = <span style="color: #CD5555">&#39;MSE Ridge train&#39;</span>)
plt.plot(np.log10(lambdas), MSEPredict, <span style="color: #CD5555">&#39;r--&#39;</span>, label = <span style="color: #CD5555">&#39;MSE Ridge Test&#39;</span>)
plt.plot(np.log10(lambdas), MSELassoTrain, label = <span style="color: #CD5555">&#39;MSE Lasso train&#39;</span>)
plt.plot(np.log10(lambdas), MSELassoPredict, <span style="color: #CD5555">&#39;r--&#39;</span>, label = <span style="color: #CD5555">&#39;MSE Lasso Test&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;log10(lambda)&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;MSE&#39;</span>)
plt.legend()
plt.show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="material-for-lecture-thursday-september-7">Material for lecture Thursday September 7 </h2>
<h2 id="important-technicalities-more-on-rescaling-data">Important technicalities: More on Rescaling data </h2>
<p>When you are comparing your own code with for example <b>Scikit-Learn</b>'s
library, there are some technicalities to keep in mind. The examples
here demonstrate some of these aspects with potential pitfalls.
</p>
<p>The discussion here focuses on the role of the intercept, how we can
set up the design matrix, what scaling we should use and other topics
which tend confuse us.
</p>
<p>The intercept can be interpreted as the expected value of our
target/output variables when all other predictors are set to zero.
Thus, if we cannot assume that the expected outputs/targets are zero
when all predictors are zero (the columns in the design matrix), it
may be a bad idea to implement a model which penalizes the intercept.
Furthermore, in for example Ridge and Lasso regression, the default solutions
from the library <b>Scikit-Learn</b> (when not shrinking \( \beta_0 \)) for the unknown parameters
\( \boldsymbol{\beta} \), are derived&#160;under the assumption that both \( \boldsymbol{y} \) and
\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values.
</p>
<p>If our predictors&#160;represent different&#160;scales, then it is important to
standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each
column from the corresponding column and dividing the column with its
standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library,
the results may differ.
</p>
<p>The
<a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" target="_blank">Standardscaler</a>
function in <b>Scikit-Learn</b> does this for us. For the data sets we
have been studying in our various examples, the data are in many cases
already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a
survey of your data, with a critical assessment of them in case you need to scale the data.
</p>
<p>If you need to scale the data, not doing so will give an <em>unfair</em>
penalization of the parameters since their magnitude&#160;depends on the
scale of their corresponding&#160;predictor.
</p>
<p>Suppose as an example that you
you have an input&#160;variable given by the heights of different persons.
Human height might be measured in inches or meters or
kilometers. If measured in kilometers, a&#160;standard linear regression
model with this predictor would probably give a much bigger
coefficient term, than if measured in millimeters.
This can clearly lead to problems in evaluating the cost/loss functions.
</p>
<p>Keep in mind that when you transform your data set before training a model, the same transformation needs to be done
on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as
</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #CD5555">&quot;&quot;&quot;</span>
<span style="color: #CD5555">#Model training, we compute the mean value of y and X</span>
<span style="color: #CD5555">y_train_mean = np.mean(y_train)</span>
<span style="color: #CD5555">X_train_mean = np.mean(X_train,axis=0)</span>
<span style="color: #CD5555">X_train = X_train - X_train_mean</span>
<span style="color: #CD5555">y_train = y_train - y_train_mean</span>
<span style="color: #CD5555"># The we fit our model with the training data</span>
<span style="color: #CD5555">trained_model = some_model.fit(X_train,y_train)</span>
<span style="color: #CD5555">#Model prediction, we need also to transform our data set used for the prediction.</span>
<span style="color: #CD5555">X_test = X_test - X_train_mean #Use mean from training data</span>
<span style="color: #CD5555">y_pred = trained_model(X_test)</span>
<span style="color: #CD5555">y_pred = y_pred + y_train_mean</span>
<span style="color: #CD5555">&quot;&quot;&quot;</span>
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>Let us try to understand what this may imply mathematically when we
subtract the mean values, also known as <em>zero centering</em>. For
simplicity, we will focus on ordinary regression, as done in the above example.
</p>
<p>The cost/loss function for regression is</p>
$$
C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,.
$$
<p>Recall also that we use the squared value. This expression can lead to an
increased penalty for higher differences between predicted and
output/target values.
</p>
<p>What we have done is to single out the \( \beta_0 \) term in the
definition of the mean squared error (MSE). The design matrix \( X \)
does in this case not contain any intercept column. When we take the
derivative with respect to \( \beta_0 \), we want the derivative to obey
</p>
$$
\frac{\partial C}{\partial \beta_j} = 0,
$$
<p>for all \( j \). For \( \beta_0 \) we have</p>
$$
\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right).
$$
<p>Multiplying away the constant \( 2/n \), we obtain</p>
$$
\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j.
$$
<p>Let us specialize first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \).
Our result for \( \beta_0 \) simplifies then to
</p>
$$
n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1.
$$
<p>We obtain then</p>
$$
\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}.
$$
<p>If we define</p>
$$
\mu_{\boldsymbol{x}_1}=\frac{1}{n}\sum_{i=0}^{n-1} X_{i1},
$$
<p>and the mean value of the outputs as</p>
$$
\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i,
$$
<p>we have</p>
$$
\beta_0 = \mu_y - \beta_1\mu_{\boldsymbol{x}_1}.
$$
<p>In the general case with more parameters than \( \beta_0 \) and \( \beta_1 \), we have</p>
$$
\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j.
$$
<p>We can rewrite the latter equation as</p>
$$
\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \sum_{j=1}^{p-1} \mu_{\boldsymbol{x}_j}\beta_j,
$$
<p>where we have defined</p>
$$
\mu_{\boldsymbol{x}_j}=\frac{1}{n}\sum_{i=0}^{n-1} X_{ij},
$$
<p>the mean value for all elements of the column vector \( \boldsymbol{x}_j \).</p>
<p>Replacing \( y_i \) with \( y_i - y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)</p>
$$
C(\boldsymbol{\beta}) = (\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta})^T(\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta}).
$$
<p>If we minimize with respect to \( \boldsymbol{\beta} \) we have then</p>
$$
\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}},
$$
<p>where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \)
and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \).
</p>
<p>For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then</p>
$$
\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}.
$$
<p>What does this mean? And why do we insist on all this? Let us look at some examples.</p>
<p>This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (<em>code example thanks to &#216;yvind Sigmundson Sch&#248;yen</em>). Here our scaling of the data is done by subtracting the mean values only.
Note also that we do not split the data into training and test.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.linear_model</span> <span style="color: #8B008B; font-weight: bold">import</span> LinearRegression
np.random.seed(<span style="color: #B452CD">2021</span>)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">MSE</span>(y_data,y_model):
n = np.size(y_model)
<span style="color: #8B008B; font-weight: bold">return</span> np.sum((y_data-y_model)**<span style="color: #B452CD">2</span>)/n
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">fit_beta</span>(X, y):
<span style="color: #8B008B; font-weight: bold">return</span> np.linalg.pinv(X.T @ X) @ X.T @ y
true_beta = [<span style="color: #B452CD">2</span>, <span style="color: #B452CD">0.5</span>, <span style="color: #B452CD">3.7</span>]
x = np.linspace(<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">11</span>)
y = np.sum(
np.asarray([x ** p * b <span style="color: #8B008B; font-weight: bold">for</span> p, b <span style="color: #8B008B">in</span> <span style="color: #658b00">enumerate</span>(true_beta)]), axis=<span style="color: #B452CD">0</span>
) + <span style="color: #B452CD">0.1</span> * np.random.normal(size=<span style="color: #658b00">len</span>(x))
degree = <span style="color: #B452CD">3</span>
X = np.zeros((<span style="color: #658b00">len</span>(x), degree))
<span style="color: #228B22"># Include the intercept in the design matrix</span>
<span style="color: #8B008B; font-weight: bold">for</span> p <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(degree):
X[:, p] = x ** p
beta = fit_beta(X, y)
<span style="color: #228B22"># Intercept is included in the design matrix</span>
skl = LinearRegression(fit_intercept=<span style="color: #8B008B; font-weight: bold">False</span>).fit(X, y)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;True beta: {</span>true_beta<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;Fitted beta: {</span>beta<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;Sklearn fitted beta: {</span>skl.coef_<span style="color: #CD5555">}&quot;</span>)
ypredictOwn = X @ beta
ypredictSKL = skl.predict(X)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;MSE with intercept column&quot;</span>)
<span style="color: #658b00">print</span>(MSE(y,ypredictOwn))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;MSE with intercept column from SKL&quot;</span>)
<span style="color: #658b00">print</span>(MSE(y,ypredictSKL))
plt.figure()
plt.scatter(x, y, label=<span style="color: #CD5555">&quot;Data&quot;</span>)
plt.plot(x, X @ beta, label=<span style="color: #CD5555">&quot;Fit&quot;</span>)
plt.plot(x, skl.predict(X), label=<span style="color: #CD5555">&quot;Sklearn (fit_intercept=False)&quot;</span>)
<span style="color: #228B22"># Do not include the intercept in the design matrix</span>
X = np.zeros((<span style="color: #658b00">len</span>(x), degree - <span style="color: #B452CD">1</span>))
<span style="color: #8B008B; font-weight: bold">for</span> p <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(degree - <span style="color: #B452CD">1</span>):
X[:, p] = x ** (p + <span style="color: #B452CD">1</span>)
<span style="color: #228B22"># Intercept is not included in the design matrix</span>
skl = LinearRegression(fit_intercept=<span style="color: #8B008B; font-weight: bold">True</span>).fit(X, y)
<span style="color: #228B22"># Use centered values for X and y when computing coefficients</span>
y_offset = np.average(y, axis=<span style="color: #B452CD">0</span>)
X_offset = np.average(X, axis=<span style="color: #B452CD">0</span>)
beta = fit_beta(X - X_offset, y - y_offset)
intercept = np.mean(y_offset - X_offset @ beta)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;Manual intercept: {</span>intercept<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;Fitted beta (wiothout intercept): {</span>beta<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;Sklearn intercept: {</span>skl.intercept_<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;Sklearn fitted beta (without intercept): {</span>skl.coef_<span style="color: #CD5555">}&quot;</span>)
ypredictOwn = X @ beta
ypredictSKL = skl.predict(X)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;MSE with Manual intercept&quot;</span>)
<span style="color: #658b00">print</span>(MSE(y,ypredictOwn+intercept))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;MSE with Sklearn intercept&quot;</span>)
<span style="color: #658b00">print</span>(MSE(y,ypredictSKL))
plt.plot(x, X @ beta + intercept, <span style="color: #CD5555">&quot;--&quot;</span>, label=<span style="color: #CD5555">&quot;Fit (manual intercept)&quot;</span>)
plt.plot(x, skl.predict(X), <span style="color: #CD5555">&quot;--&quot;</span>, label=<span style="color: #CD5555">&quot;Sklearn (fit_intercept=True)&quot;</span>)
plt.grid()
plt.legend()
plt.show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>The intercept is the value of our output/target variable
when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case).
</p>
<p>Printing the MSE, we see first that both methods give the same MSE, as
they should. However, when we move to for example Ridge regression,
the way we treat the intercept may give a larger or smaller MSE,
meaning that the MSE can be penalized by the value of the
intercept. Not including the intercept in the fit, means that the
regularization term does not include \( \beta_0 \). For different values
of \( \lambda \), this may lead to different MSE values.
</p>
<p>To remind the reader, the regularization term, with the intercept in Ridge regression, is given by</p>
$$
\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2,
$$
<p>but when we take out the intercept, this equation becomes</p>
$$
\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2.
$$
<p>For Lasso regression we have</p>
$$
\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert.
$$
<p>It means that, when scaling the design matrix and the outputs/targets,
by subtracting the mean values, we have an optimization problem which
is not penalized by the intercept. The MSE value can then be smaller
since it focuses only on the remaining quantities. If we however bring
back the intercept, we will get a MSE which then contains the
intercept.
</p>
<p>Armed with this wisdom, we attempt first to simply set the intercept equal to <b>False</b> in our implementation of Ridge regression for our well-known vanilla data set.</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn</span> <span style="color: #8B008B; font-weight: bold">import</span> linear_model
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">MSE</span>(y_data,y_model):
n = np.size(y_model)
<span style="color: #8B008B; font-weight: bold">return</span> np.sum((y_data-y_model)**<span style="color: #B452CD">2</span>)/n
<span style="color: #228B22"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #228B22"># Useful for eventual debugging.</span>
np.random.seed(<span style="color: #B452CD">3155</span>)
n = <span style="color: #B452CD">100</span>
x = np.random.rand(n)
y = np.exp(-x**<span style="color: #B452CD">2</span>) + <span style="color: #B452CD">1.5</span> * np.exp(-(x-<span style="color: #B452CD">2</span>)**<span style="color: #B452CD">2</span>)
Maxpolydegree = <span style="color: #B452CD">20</span>
X = np.zeros((n,Maxpolydegree))
<span style="color: #228B22">#We include explicitely the intercept column</span>
<span style="color: #8B008B; font-weight: bold">for</span> degree <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(Maxpolydegree):
X[:,degree] = x**degree
<span style="color: #228B22"># We split the data in test and training data</span>
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=<span style="color: #B452CD">0.2</span>)
p = Maxpolydegree
I = np.eye(p,p)
<span style="color: #228B22"># Decide which values of lambda to use</span>
nlambdas = <span style="color: #B452CD">6</span>
MSEOwnRidgePredict = np.zeros(nlambdas)
MSERidgePredict = np.zeros(nlambdas)
lambdas = np.logspace(-<span style="color: #B452CD">4</span>, <span style="color: #B452CD">2</span>, nlambdas)
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(nlambdas):
lmb = lambdas[i]
OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
<span style="color: #228B22"># Note: we include the intercept column and no scaling</span>
RegRidge = linear_model.Ridge(lmb,fit_intercept=<span style="color: #8B008B; font-weight: bold">False</span>)
RegRidge.fit(X_train,y_train)
<span style="color: #228B22"># and then make the prediction</span>
ytildeOwnRidge = X_train @ OwnRidgeBeta
ypredictOwnRidge = X_test @ OwnRidgeBeta
ytildeRidge = RegRidge.predict(X_train)
ypredictRidge = RegRidge.predict(X_test)
MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
MSERidgePredict[i] = MSE(y_test,ypredictRidge)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Beta values for own Ridge implementation&quot;</span>)
<span style="color: #658b00">print</span>(OwnRidgeBeta)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Beta values for Scikit-Learn Ridge implementation&quot;</span>)
<span style="color: #658b00">print</span>(RegRidge.coef_)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;MSE values for own Ridge implementation&quot;</span>)
<span style="color: #658b00">print</span>(MSEOwnRidgePredict[i])
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;MSE values for Scikit-Learn Ridge implementation&quot;</span>)
<span style="color: #658b00">print</span>(MSERidgePredict[i])
<span style="color: #228B22"># Now plot the results</span>
plt.figure()
plt.plot(np.log10(lambdas), MSEOwnRidgePredict, <span style="color: #CD5555">&#39;r&#39;</span>, label = <span style="color: #CD5555">&#39;MSE own Ridge Test&#39;</span>)
plt.plot(np.log10(lambdas), MSERidgePredict, <span style="color: #CD5555">&#39;g&#39;</span>, label = <span style="color: #CD5555">&#39;MSE Ridge Test&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;log10(lambda)&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;MSE&#39;</span>)
plt.legend()
plt.show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>The results here agree when we force <b>Scikit-Learn</b>'s Ridge function to include the first column in our design matrix.
We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix.
What happens if we do not include the intercept in our fit?
Let us see how we can change this code by zero centering.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn</span> <span style="color: #8B008B; font-weight: bold">import</span> linear_model
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.preprocessing</span> <span style="color: #8B008B; font-weight: bold">import</span> StandardScaler
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">MSE</span>(y_data,y_model):
n = np.size(y_model)
<span style="color: #8B008B; font-weight: bold">return</span> np.sum((y_data-y_model)**<span style="color: #B452CD">2</span>)/n
<span style="color: #228B22"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #228B22"># Useful for eventual debugging.</span>
np.random.seed(<span style="color: #B452CD">315</span>)
n = <span style="color: #B452CD">100</span>
x = np.random.rand(n)
y = np.exp(-x**<span style="color: #B452CD">2</span>) + <span style="color: #B452CD">1.5</span> * np.exp(-(x-<span style="color: #B452CD">2</span>)**<span style="color: #B452CD">2</span>)
Maxpolydegree = <span style="color: #B452CD">20</span>
X = np.zeros((n,Maxpolydegree-<span style="color: #B452CD">1</span>))
<span style="color: #8B008B; font-weight: bold">for</span> degree <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">1</span>,Maxpolydegree): <span style="color: #228B22">#No intercept column</span>
X[:,degree-<span style="color: #B452CD">1</span>] = x**(degree)
<span style="color: #228B22"># We split the data in test and training data</span>
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=<span style="color: #B452CD">0.2</span>)
<span style="color: #228B22">#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable</span>
X_train_mean = np.mean(X_train,axis=<span style="color: #B452CD">0</span>)
<span style="color: #228B22">#Center by removing mean from each feature</span>
X_train_scaled = X_train - X_train_mean
X_test_scaled = X_test - X_train_mean
<span style="color: #228B22">#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered)</span>
<span style="color: #228B22">#Remove the intercept from the training data.</span>
y_scaler = np.mean(y_train)
y_train_scaled = y_train - y_scaler
p = Maxpolydegree-<span style="color: #B452CD">1</span>
I = np.eye(p,p)
<span style="color: #228B22"># Decide which values of lambda to use</span>
nlambdas = <span style="color: #B452CD">6</span>
MSEOwnRidgePredict = np.zeros(nlambdas)
MSERidgePredict = np.zeros(nlambdas)
lambdas = np.logspace(-<span style="color: #B452CD">4</span>, <span style="color: #B452CD">2</span>, nlambdas)
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(nlambdas):
lmb = lambdas[i]
OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled)
intercept_ = y_scaler - X_train_mean<span style="color: #707a7c">@OwnRidgeBeta</span> <span style="color: #228B22">#The intercept can be shifted so the model can predict on uncentered data</span>
<span style="color: #228B22">#Add intercept to prediction</span>
ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler
RegRidge = linear_model.Ridge(lmb)
RegRidge.fit(X_train,y_train)
ypredictRidge = RegRidge.predict(X_test)
MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
MSERidgePredict[i] = MSE(y_test,ypredictRidge)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Beta values for own Ridge implementation&quot;</span>)
<span style="color: #658b00">print</span>(OwnRidgeBeta) <span style="color: #228B22">#Intercept is given by mean of target variable</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Beta values for Scikit-Learn Ridge implementation&quot;</span>)
<span style="color: #658b00">print</span>(RegRidge.coef_)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;Intercept from own implementation:&#39;</span>)
<span style="color: #658b00">print</span>(intercept_)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;Intercept from Scikit-Learn Ridge implementation&#39;</span>)
<span style="color: #658b00">print</span>(RegRidge.intercept_)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;MSE values for own Ridge implementation&quot;</span>)
<span style="color: #658b00">print</span>(MSEOwnRidgePredict[i])
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;MSE values for Scikit-Learn Ridge implementation&quot;</span>)
<span style="color: #658b00">print</span>(MSERidgePredict[i])
<span style="color: #228B22"># Now plot the results</span>
plt.figure()
plt.plot(np.log10(lambdas), MSEOwnRidgePredict, <span style="color: #CD5555">&#39;b--&#39;</span>, label = <span style="color: #CD5555">&#39;MSE own Ridge Test&#39;</span>)
plt.plot(np.log10(lambdas), MSERidgePredict, <span style="color: #CD5555">&#39;g--&#39;</span>, label = <span style="color: #CD5555">&#39;MSE SL Ridge Test&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;log10(lambda)&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;MSE&#39;</span>)
plt.legend()
plt.show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>We see here, when compared to the code which includes explicitely the
intercept column, that our MSE value is actually smaller. This is
because the regularization term does not include the intercept value
\( \beta_0 \) in the fitting. This applies to Lasso regularization as
well. It means that our optimization is now done only with the
centered matrix and/or vector that enter the fitting procedure.
</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>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>
<p>Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit. </p>
<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>
<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 "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn</span> <span style="color: #8B008B; font-weight: bold">import</span> linear_model
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">R2</span>(y_data, y_model):
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">1</span> - np.sum((y_data - y_model) ** <span style="color: #B452CD">2</span>) / np.sum((y_data - np.mean(y_data)) ** <span style="color: #B452CD">2</span>)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">MSE</span>(y_data,y_model):
n = np.size(y_model)
<span style="color: #8B008B; font-weight: bold">return</span> np.sum((y_data-y_model)**<span style="color: #B452CD">2</span>)/n
<span style="color: #228B22"># Make data set.</span>
n = <span style="color: #B452CD">10000</span>
x = np.random.rand(n)
y = np.exp(-x**<span style="color: #B452CD">2</span>) + <span style="color: #B452CD">1.5</span> * np.exp(-(x-<span style="color: #B452CD">2</span>)**<span style="color: #B452CD">2</span>)+ np.random.randn(n)
Maxpolydegree = <span style="color: #B452CD">5</span>
X = np.zeros((<span style="color: #658b00">len</span>(x),Maxpolydegree))
X[:,<span style="color: #B452CD">0</span>] = <span style="color: #B452CD">1.0</span>
<span style="color: #8B008B; font-weight: bold">for</span> polydegree <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">1</span>,Maxpolydegree):
X[:,polydegree] = x**(polydegree)
<span style="color: #228B22"># We split the data in test and training data</span>
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=<span style="color: #B452CD">0.2</span>)
<span style="color: #228B22"># matrix inversion to find beta</span>
OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train
<span style="color: #658b00">print</span>(OLSbeta)
ypredictOLS = X_test @ OLSbeta
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test MSE OLS&quot;</span>)
<span style="color: #658b00">print</span>(MSE(y_test,ypredictOLS))
<span style="color: #228B22"># Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn</span>
<span style="color: #228B22"># Decide which values of lambda to use</span>
nlambdas = <span style="color: #B452CD">4</span>
MSERidgePredict = np.zeros(nlambdas)
MSELassoPredict = np.zeros(nlambdas)
lambdas = np.logspace(-<span style="color: #B452CD">3</span>, <span style="color: #B452CD">1</span>, nlambdas)
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(nlambdas):
lmb = lambdas[i]
<span style="color: #228B22"># Make the fit using Ridge and Lasso</span>
RegRidge = linear_model.Ridge(lmb,fit_intercept=<span style="color: #8B008B; font-weight: bold">False</span>)
RegRidge.fit(X_train,y_train)
RegLasso = linear_model.Lasso(lmb,fit_intercept=<span style="color: #8B008B; font-weight: bold">False</span>)
RegLasso.fit(X_train,y_train)
<span style="color: #228B22"># and then make the prediction</span>
ypredictRidge = RegRidge.predict(X_test)
ypredictLasso = RegLasso.predict(X_test)
<span style="color: #228B22"># Compute the MSE and print it</span>
MSERidgePredict[i] = MSE(y_test,ypredictRidge)
MSELassoPredict[i] = MSE(y_test,ypredictLasso)
<span style="color: #658b00">print</span>(lmb,RegRidge.coef_)
<span style="color: #658b00">print</span>(lmb,RegLasso.coef_)
<span style="color: #228B22"># Now plot the results</span>
plt.figure()
plt.plot(np.log10(lambdas), MSERidgePredict, <span style="color: #CD5555">&#39;b&#39;</span>, label = <span style="color: #CD5555">&#39;MSE Ridge Test&#39;</span>)
plt.plot(np.log10(lambdas), MSELassoPredict, <span style="color: #CD5555">&#39;r&#39;</span>, label = <span style="color: #CD5555">&#39;MSE Lasso Test&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;log10(lambda)&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;MSE&#39;</span>)
plt.legend()
plt.show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>How can we understand this? </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>
<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>
<p>It is assumed that \( \varepsilon_i
\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are
independent, i.e.:
</p>
$$
\begin{align*}
\mbox{Cov}(\varepsilon_{i_1},
\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
\end{align*}
$$
<p>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>
<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
</p>
$$
\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
</p>
$$
\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
$$
<!-- !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 \) </p>
$$
\begin{align*}
\mathbb{E}(y_i) & =
\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i)
\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
\end{align*}
$$
<p>while
its variance is
</p>
$$
\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*}
$$
<p>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 optimal parameters \( \boldsymbol{\hat{\beta}} \) we can evaluate the expectation value</p>
$$
\mathbb{E}(\boldsymbol{\hat{\beta}}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}.
$$
<p>This means that the estimator of the regression parameters is unbiased.</p>
<p>We can also calculate the variance</p>
<p>The variance of the optimal value \( \boldsymbol{\hat{\beta}} \) is</p>
$$
\begin{eqnarray*}
\mbox{Var}(\boldsymbol{\hat{\beta}}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \}
\\
& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \}
\\
% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
% \\
% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
% \\
& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
\\
& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
% \\
% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
% \\
% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T
\\
& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
\end{eqnarray*}
$$
<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>
<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>
<p>It is rather straightforward to show that</p>
$$
\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}}.
$$
<p>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>
<p>We can also compute the variance as </p>
$$
\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T},
$$
<p>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>
<p>With this, we can compute the difference </p>
$$
\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}.
$$
<p>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>
<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
</p>
$$
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]}.
$$
<!-- !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>
$$
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]},
$$
<p>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>
<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>
$$
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
</p>
$$
\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
$$
<p>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>
$$
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>
<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>
<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>
<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</p>
$$
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})},
$$
<p>which becomes</p>
$$
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</p>
$$
\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0,
$$
<p>which leads to the well-known OLS equation for the optimal paramters \( \beta \)</p>
$$
\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>
<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>
<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>
<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),
$$
<p>where we read \( p(X\vert Y) \) as the likelihood of obtaining \( X \) given \( Y \).</p>
</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</p>
<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>
<!-- !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 </p>
<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>
<!-- !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>
$$
p(X\vert Y)= \frac{p(X,Y)}{p(Y)},
$$
<p>which we can rewrite as</p>
$$
p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)},
$$
<p>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>
<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>
<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>
<p>We let \( Y=1 \) represent the the case of having breast cancer and \( Y=0 \) as not.</p>
<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>
$$
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>
$$
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>
$$
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>
$$
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.
$$
<p>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>Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. </p>
<p>For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case)</p>
$$
\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})],
$$
<p>is given by</p>
$$
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>
$$
p(\boldsymbol{\beta}\vert\boldsymbol{D}).
$$
<p>Bayes' theorem comes to our rescue here since (omitting the normalization constant)</p>
$$
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>
<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>
$$
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>
$$
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
</p>
$$
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,
$$
<p>and replacing \( 1/2\tau^2 \) with \( \lambda \) we have</p>
$$
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,
$$
<p>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>
$$
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>
$$
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
</p>
$$
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,
$$
<p>and replacing \( 1/\tau \) with \( \lambda \) we have</p>
$$
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,
$$
<p>which is our Lasso cost function! </p>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>