982 lines
52 KiB
HTML
982 lines
52 KiB
HTML
<!--
|
|
HTML file automatically generated from DocOnce source
|
|
(https://github.com/doconce/doconce/)
|
|
doconce format html week36.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=week36 --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: Linear Regression and Gradient descent">
|
|
<title>Week 36: Linear Regression and Gradient descent</title>
|
|
<style type="text/css">
|
|
/* bloodish style */
|
|
body {
|
|
font-family: Helvetica, Verdana, Arial, Sans-serif;
|
|
color: #404040;
|
|
background: #ffffff;
|
|
}
|
|
h1 { font-size: 1.8em; color: #8A0808; }
|
|
h2 { font-size: 1.6em; color: #8A0808; }
|
|
h3 { font-size: 1.4em; color: #8A0808; }
|
|
h4 { font-size: 1.2em; color: #8A0808; }
|
|
a { color: #8A0808; text-decoration:none; }
|
|
tt { font-family: "Courier New", Courier; }
|
|
p { text-indent: 0px; }
|
|
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
|
|
p.caption { width: 80%; font-style: normal; text-align: left; }
|
|
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa; }div.highlight {
|
|
border: 1px solid #cfcfcf;
|
|
border-radius: 2px;
|
|
line-height: 1.21429em;
|
|
}
|
|
div.cell {
|
|
width: 100%;
|
|
padding: 5px 5px 5px 0;
|
|
margin: 0;
|
|
outline: none;
|
|
}
|
|
div.input {
|
|
page-break-inside: avoid;
|
|
box-orient: horizontal;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: row;
|
|
align-items: stretch;
|
|
}
|
|
div.inner_cell {
|
|
box-orient: vertical;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: stretch;
|
|
box-flex: 1;
|
|
flex: 1;
|
|
}
|
|
div.input_area {
|
|
border: 1px solid #cfcfcf;
|
|
border-radius: 4px;
|
|
background: #f7f7f7;
|
|
line-height: 1.21429em;
|
|
}
|
|
div.input_area > div.highlight {
|
|
margin: .4em;
|
|
border: none;
|
|
padding: 0;
|
|
background-color: transparent;
|
|
}
|
|
div.output_wrapper {
|
|
position: relative;
|
|
box-orient: vertical;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: stretch;
|
|
}
|
|
.output {
|
|
box-orient: vertical;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: stretch;
|
|
}
|
|
div.output_area {
|
|
padding: 0;
|
|
page-break-inside: avoid;
|
|
box-orient: horizontal;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: row;
|
|
align-items: stretch;
|
|
}
|
|
div.output_subarea {
|
|
padding: .4em .4em 0 .4em;
|
|
box-flex: 1;
|
|
flex: 1;
|
|
}
|
|
div.output_text {
|
|
text-align: left;
|
|
color: #000;
|
|
line-height: 1.21429em;
|
|
}
|
|
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 lecture Monday September 2',
|
|
2,
|
|
None,
|
|
'material-for-lecture-monday-september-2'),
|
|
('Material for lab sessions sessions Tuesday and Wednesday',
|
|
2,
|
|
None,
|
|
'material-for-lab-sessions-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'),
|
|
('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')]}
|
|
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: Linear Regression and Gradient descent</h1>
|
|
</center> <!-- document title -->
|
|
|
|
<!-- author(s): Morten Hjorth-Jensen -->
|
|
<center>
|
|
<b>Morten Hjorth-Jensen</b>
|
|
</center>
|
|
<!-- institution -->
|
|
<center>
|
|
<b>Department of Physics, University of Oslo, Norway</b>
|
|
</center>
|
|
<br>
|
|
<center>
|
|
<h4>September 1-5, 2025</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 lecture on Monday September 2
|
|
<ol type="a"></li>
|
|
<li> Linear Regression, ordinary least squares (OLS), Ridge and Lasso and mathematical analysis</li>
|
|
<li> Derivation of Gradient descent and discussion of implementations for
|
|
<!-- * <a href="https://youtu.be/oHjqjUB36KE" target="_blank">Video of lecture</a> -->
|
|
<!-- * <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesSeptember2.pdf" target="_blank">Whiteboard notes</a> --></li>
|
|
</ol>
|
|
<li> Material for the active learning sessions on Tuesday and Wednesday (see at the end of this slides)</li>
|
|
<ul>
|
|
<li> Technicalities concerning Ridge and Lasso linear regression.</li>
|
|
<li> Presentation and discussion of the first project
|
|
<!-- * <a href="https://youtu.be/ZrIdZdZtHe0" target="_blank">Video of lab session</a> --></li>
|
|
</ul>
|
|
<li> Reading suggestion:
|
|
<ol type="a"></li>
|
|
<li> Goodfellow et al, Deep Learning, introduction to gradient descent, see chapter 4.3 at <a href="https://www.deeplearningbook.org/contents/numerical.html" target="_blank"><tt>https://www.deeplearningbook.org/contents/numerical.html</tt></a></li>
|
|
<li> Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.</li>
|
|
</ol>
|
|
</ul>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="material-for-lecture-monday-september-2">Material for lecture Monday September 2 </h2>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="material-for-lab-sessions-sessions-tuesday-and-wednesday">Material for lab sessions sessions Tuesday and Wednesday </h2>
|
|
|
|
<p>The material here contains a summary of the lecture on Monday 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>
|
|
|
|
<!-- !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> and using our own gradient descent code in project 1.</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 "default" -->
|
|
<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: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
|
|
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># A seed just to ensure that the random numbers are the same for every run.</span>
|
|
<span style="color: #408080; font-style: italic"># Useful for eventual debugging.</span>
|
|
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ [ <span style="color: #666666">2</span>, <span style="color: #666666">0</span>], [<span style="color: #666666">0</span>, <span style="color: #666666">1</span>], [<span style="color: #666666">0</span>,<span style="color: #666666">0</span>]])
|
|
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [<span style="color: #666666">4</span>, <span style="color: #666666">2</span>, <span style="color: #666666">3</span>])
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
|
|
OLSbeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X) <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
|
|
<span style="color: #008000">print</span>(OLSbeta)
|
|
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
|
|
ytildeOLS <span style="color: #666666">=</span> X <span style="color: #666666">@</span> OLSbeta
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Training MSE for OLS"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y,ytildeOLS))
|
|
ypredictOLS <span style="color: #666666">=</span> X <span style="color: #666666">@</span> OLSbeta
|
|
|
|
<span style="color: #408080; font-style: italic"># Repeat now for Ridge regression and various values of the regularization parameter</span>
|
|
I <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(<span style="color: #666666">2</span>,<span style="color: #666666">2</span>)
|
|
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
|
|
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
MSEPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">4</span>, nlambdas)
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(nlambdas):
|
|
lmb <span style="color: #666666">=</span> lambdas[i]
|
|
Ridgebeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X<span style="color: #666666">+</span>lmb<span style="color: #666666">*</span>I) <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
|
|
<span style="color: #408080; font-style: italic"># print(Ridgebeta)</span>
|
|
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
|
|
ypredictRidge <span style="color: #666666">=</span> X <span style="color: #666666">@</span> Ridgebeta
|
|
MSEPredict[i] <span style="color: #666666">=</span> MSE(y,ypredictRidge)
|
|
<span style="color: #408080; font-style: italic"># print(MSEPredict[i])</span>
|
|
<span style="color: #408080; font-style: italic"># Now plot the results</span>
|
|
plt<span style="color: #666666">.</span>figure()
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSEPredict, <span style="color: #BA2121">'r--'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE Ridge Train'</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'log10(lambda)'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'MSE'</span>)
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>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 "default" -->
|
|
<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: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> linear_model
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
|
|
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># A seed just to ensure that the random numbers are the same for every run.</span>
|
|
<span style="color: #408080; font-style: italic"># Useful for eventual debugging.</span>
|
|
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ [ <span style="color: #666666">2</span>, <span style="color: #666666">0</span>], [<span style="color: #666666">0</span>, <span style="color: #666666">1</span>], [<span style="color: #666666">0</span>,<span style="color: #666666">0</span>]])
|
|
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [<span style="color: #666666">4</span>, <span style="color: #666666">2</span>, <span style="color: #666666">3</span>])
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
|
|
OLSbeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X) <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
|
|
<span style="color: #008000">print</span>(OLSbeta)
|
|
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
|
|
ytildeOLS <span style="color: #666666">=</span> X <span style="color: #666666">@</span> OLSbeta
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Training MSE for OLS"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y,ytildeOLS))
|
|
ypredictOLS <span style="color: #666666">=</span> X <span style="color: #666666">@</span> OLSbeta
|
|
|
|
<span style="color: #408080; font-style: italic"># Repeat now for Ridge regression and various values of the regularization parameter</span>
|
|
I <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(<span style="color: #666666">2</span>,<span style="color: #666666">2</span>)
|
|
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
|
|
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
MSERidgePredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
MSELassoPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">4</span>, nlambdas)
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(nlambdas):
|
|
lmb <span style="color: #666666">=</span> lambdas[i]
|
|
Ridgebeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X<span style="color: #666666">+</span>lmb<span style="color: #666666">*</span>I) <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
|
|
<span style="color: #008000">print</span>(Ridgebeta)
|
|
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
|
|
ypredictRidge <span style="color: #666666">=</span> X <span style="color: #666666">@</span> Ridgebeta
|
|
MSERidgePredict[i] <span style="color: #666666">=</span> MSE(y,ypredictRidge)
|
|
RegLasso <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>Lasso(lmb,fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
|
|
RegLasso<span style="color: #666666">.</span>fit(X,y)
|
|
ypredictLasso <span style="color: #666666">=</span> RegLasso<span style="color: #666666">.</span>predict(X)
|
|
<span style="color: #008000">print</span>(RegLasso<span style="color: #666666">.</span>coef_)
|
|
MSELassoPredict[i] <span style="color: #666666">=</span> MSE(y,ypredictLasso)
|
|
<span style="color: #408080; font-style: italic"># Now plot the results</span>
|
|
plt<span style="color: #666666">.</span>figure()
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSERidgePredict, <span style="color: #BA2121">'r--'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE Ridge Train'</span>)
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSELassoPredict, <span style="color: #BA2121">'r--'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE Lasso Train'</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'log10(lambda)'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'MSE'</span>)
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>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 "default" -->
|
|
<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: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> linear_model
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
|
|
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># A seed just to ensure that the random numbers are the same for every run.</span>
|
|
<span style="color: #408080; font-style: italic"># Useful for eventual debugging.</span>
|
|
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">3155</span>)
|
|
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">2.0+5*</span>x<span style="color: #666666">*</span>x<span style="color: #666666">+0.1*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># number of features p (here degree of polynomial</span>
|
|
p <span style="color: #666666">=</span> <span style="color: #666666">3</span>
|
|
<span style="color: #408080; font-style: italic"># The design matrix now as function of a given polynomial</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(x),p))
|
|
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
|
|
X[:,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> x
|
|
X[:,<span style="color: #666666">2</span>] <span style="color: #666666">=</span> x<span style="color: #666666">*</span>x
|
|
<span style="color: #408080; font-style: italic"># We split the data in test and training data</span>
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
|
|
OLSbeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
|
|
<span style="color: #008000">print</span>(OLSbeta)
|
|
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
|
|
ytildeOLS <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> OLSbeta
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Training MSE for OLS"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y_train,ytildeOLS))
|
|
ypredictOLS <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> OLSbeta
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test MSE OLS"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y_test,ypredictOLS))
|
|
|
|
<span style="color: #408080; font-style: italic"># Repeat now for Lasso and Ridge regression and various values of the regularization parameter</span>
|
|
I <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(p,p)
|
|
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
|
|
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
MSEPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
MSETrain <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
MSELassoPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
MSELassoTrain <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">4</span>, nlambdas)
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(nlambdas):
|
|
lmb <span style="color: #666666">=</span> lambdas[i]
|
|
Ridgebeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train<span style="color: #666666">+</span>lmb<span style="color: #666666">*</span>I) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
|
|
<span style="color: #408080; font-style: italic"># include lasso using Scikit-Learn</span>
|
|
RegLasso <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>Lasso(lmb,fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
|
|
RegLasso<span style="color: #666666">.</span>fit(X_train,y_train)
|
|
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
|
|
ytildeRidge <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> Ridgebeta
|
|
ypredictRidge <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> Ridgebeta
|
|
ytildeLasso <span style="color: #666666">=</span> RegLasso<span style="color: #666666">.</span>predict(X_train)
|
|
ypredictLasso <span style="color: #666666">=</span> RegLasso<span style="color: #666666">.</span>predict(X_test)
|
|
MSEPredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictRidge)
|
|
MSETrain[i] <span style="color: #666666">=</span> MSE(y_train,ytildeRidge)
|
|
MSELassoPredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictLasso)
|
|
MSELassoTrain[i] <span style="color: #666666">=</span> MSE(y_train,ytildeLasso)
|
|
|
|
<span style="color: #408080; font-style: italic"># Now plot the results</span>
|
|
plt<span style="color: #666666">.</span>figure()
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSETrain, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE Ridge train'</span>)
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSEPredict, <span style="color: #BA2121">'r--'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE Ridge Test'</span>)
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSELassoTrain, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE Lasso train'</span>)
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSELassoPredict, <span style="color: #BA2121">'r--'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE Lasso Test'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'log10(lambda)'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'MSE'</span>)
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>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>
|
|
|
|
|
|
<!-- ------------------- end of main content --------------- -->
|
|
<center style="font-size:80%">
|
|
<!-- copyright --> © 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
|
</center>
|
|
</body>
|
|
</html>
|
|
|