wrong file, now correct
This commit is contained in:
@@ -8,7 +8,8 @@ doconce format html Project1.do.txt --html_style=bootstrap --pygments_html_style
|
||||
<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" />
|
||||
<title></title>
|
||||
<meta name="description" content="Project 1 on Machine Learning, deadline October 7, 2022">
|
||||
<title>Project 1 on Machine Learning, deadline October 7, 2022</title>
|
||||
<!-- Bootstrap style: bootstrap -->
|
||||
<!-- doconce format html Project1.do.txt --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=Project1-bs -->
|
||||
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
|
||||
@@ -35,7 +36,52 @@ doconce format html Project1.do.txt --html_style=bootstrap --pygments_html_style
|
||||
|
||||
<!-- tocinfo
|
||||
{'highest level': 2,
|
||||
'sections': [('Format for electronic delivery of report and programs',
|
||||
'sections': [('Regression analysis and resampling methods',
|
||||
2,
|
||||
None,
|
||||
'regression-analysis-and-resampling-methods'),
|
||||
('Description of two-dimensional function',
|
||||
3,
|
||||
None,
|
||||
'description-of-two-dimensional-function'),
|
||||
('Part a): Paper and pencil part (also as weekly exercise for '
|
||||
'week 36)',
|
||||
3,
|
||||
None,
|
||||
'part-a-paper-and-pencil-part-also-as-weekly-exercise-for-week-36'),
|
||||
('Part b) : Ordinary Least Square (OLS) on the Franke function',
|
||||
3,
|
||||
None,
|
||||
'part-b-ordinary-least-square-ols-on-the-franke-function'),
|
||||
('Part c): Bias-variance trade-off and resampling techniques',
|
||||
3,
|
||||
None,
|
||||
'part-c-bias-variance-trade-off-and-resampling-techniques'),
|
||||
('Part d): Cross-validation as resampling techniques, adding '
|
||||
'more complexity',
|
||||
3,
|
||||
None,
|
||||
'part-d-cross-validation-as-resampling-techniques-adding-more-complexity'),
|
||||
('Part e): Ridge Regression on the Franke function with '
|
||||
'resampling',
|
||||
3,
|
||||
None,
|
||||
'part-e-ridge-regression-on-the-franke-function-with-resampling'),
|
||||
('Part f): Lasso Regression on the Franke function with '
|
||||
'resampling',
|
||||
3,
|
||||
None,
|
||||
'part-f-lasso-regression-on-the-franke-function-with-resampling'),
|
||||
('Part g): Analysis of real data',
|
||||
3,
|
||||
None,
|
||||
'part-g-analysis-of-real-data'),
|
||||
('Background literature', 2, None, 'background-literature'),
|
||||
('Introduction to numerical projects',
|
||||
2,
|
||||
None,
|
||||
'introduction-to-numerical-projects'),
|
||||
('Format for electronic delivery of report and programs',
|
||||
2,
|
||||
None,
|
||||
'format-for-electronic-delivery-of-report-and-programs'),
|
||||
@@ -46,10 +92,571 @@ doconce format html Project1.do.txt --html_style=bootstrap --pygments_html_style
|
||||
end of tocinfo -->
|
||||
|
||||
<body>
|
||||
|
||||
|
||||
|
||||
<script type="text/x-mathjax-config">
|
||||
MathJax.Hub.Config({
|
||||
TeX: {
|
||||
equationNumbers: { autoNumber: "none" },
|
||||
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>
|
||||
|
||||
|
||||
<!-- Bootstrap navigation bar -->
|
||||
<div class="navbar navbar-default navbar-fixed-top">
|
||||
<div class="navbar-header">
|
||||
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">
|
||||
<span class="icon-bar"></span>
|
||||
<span class="icon-bar"></span>
|
||||
<span class="icon-bar"></span>
|
||||
</button>
|
||||
<a class="navbar-brand" href="Project1-bs.html">Project 1 on Machine Learning, deadline October 7, 2022</a>
|
||||
</div>
|
||||
<div class="navbar-collapse collapse navbar-responsive-collapse">
|
||||
<ul class="nav navbar-nav navbar-right">
|
||||
<li class="dropdown">
|
||||
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
|
||||
<ul class="dropdown-menu">
|
||||
<!-- navigation toc: --> <li><a href="#regression-analysis-and-resampling-methods" style="font-size: 80%;"><b>Regression analysis and resampling methods</b></a></li>
|
||||
<!-- navigation toc: --> <li><a href="#description-of-two-dimensional-function" style="font-size: 80%;"> Description of two-dimensional function</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-a-paper-and-pencil-part-also-as-weekly-exercise-for-week-36" style="font-size: 80%;"> Part a): Paper and pencil part (also as weekly exercise for week 36)</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-b-ordinary-least-square-ols-on-the-franke-function" style="font-size: 80%;"> Part b) : Ordinary Least Square (OLS) on the Franke function</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-c-bias-variance-trade-off-and-resampling-techniques" style="font-size: 80%;"> Part c): Bias-variance trade-off and resampling techniques</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-d-cross-validation-as-resampling-techniques-adding-more-complexity" style="font-size: 80%;"> Part d): Cross-validation as resampling techniques, adding more complexity</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-e-ridge-regression-on-the-franke-function-with-resampling" style="font-size: 80%;"> Part e): Ridge Regression on the Franke function with resampling</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-f-lasso-regression-on-the-franke-function-with-resampling" style="font-size: 80%;"> Part f): Lasso Regression on the Franke function with resampling</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-g-analysis-of-real-data" style="font-size: 80%;"> Part g): Analysis of real data</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#background-literature" style="font-size: 80%;"><b>Background literature</b></a></li>
|
||||
<!-- navigation toc: --> <li><a href="#introduction-to-numerical-projects" style="font-size: 80%;"><b>Introduction to numerical projects</b></a></li>
|
||||
<!-- navigation toc: --> <li><a href="#format-for-electronic-delivery-of-report-and-programs" style="font-size: 80%;"><b>Format for electronic delivery of report and programs</b></a></li>
|
||||
<!-- navigation toc: --> <li><a href="#software-and-needed-installations" style="font-size: 80%;"><b>Software and needed installations</b></a></li>
|
||||
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div> <!-- end of navigation bar -->
|
||||
<div class="container">
|
||||
<p> </p><p> </p><p> </p> <!-- add vertical space -->
|
||||
<a name="part0000"></a>
|
||||
<!-- ------------------- main content ---------------------- -->
|
||||
<div class="jumbotron">
|
||||
<center>
|
||||
<h1>Project 1 on Machine Learning, deadline October 7, 2022</h1>
|
||||
</center> <!-- document title -->
|
||||
|
||||
<!-- author(s): <a href="http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" target="_self">Data Analysis and Machine Learning FYS-STK3155/FYS4155</a> -->
|
||||
<center>
|
||||
<b><a href="http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" target="_self">Data Analysis and Machine Learning FYS-STK3155/FYS4155</a></b>
|
||||
</center>
|
||||
<!-- institution -->
|
||||
<center>
|
||||
<b>University of Oslo, Norway</b>
|
||||
</center>
|
||||
<br>
|
||||
<center>
|
||||
<h4>Sep 7, 2022</h4>
|
||||
</center> <!-- date -->
|
||||
<br>
|
||||
|
||||
|
||||
</div> <!-- end jumbotron -->
|
||||
<h2 id="regression-analysis-and-resampling-methods" class="anchor">Regression analysis and resampling methods </h2>
|
||||
|
||||
<p>The main aim of this project is to study in more detail various
|
||||
regression methods, including the Ordinary Least Squares (OLS) method.
|
||||
In addition to the scientific part, in this course we want also to
|
||||
give you an experience in writing scientific reports. The format for
|
||||
the delivery of your answers is namely that of a scientific report. At
|
||||
for example
|
||||
<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md" target="_self"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md</tt></a>
|
||||
we detail how to write a report. Furthermore, at
|
||||
<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/" target="_self"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/</tt></a>
|
||||
you can find examples of previous reports. How to write reports will
|
||||
also be discussed during lectures and at the various lab sessions.
|
||||
</p>
|
||||
|
||||
<p><b>A small recommendation when developing the codes here</b>. Instead of
|
||||
jumping on to the two-dimensional function described below, we
|
||||
recommend to do the code development and testing with a simpler
|
||||
one-dimensional function, similar to those discussed in the exercises
|
||||
of week 35. A simple test, as discussed during the lectures the first
|
||||
two weeks is to set the design matrix equal to the identity
|
||||
matrix. Then your model should give a mean square error which is exactly equal to zero.
|
||||
When you are sure that your codes function well, you can then replace
|
||||
the one-dimensional test function with the two-dimensional <b>Franke</b> function
|
||||
discussed here.
|
||||
</p>
|
||||
|
||||
<p>The Franke function serves as a stepping stone towards the analysis of
|
||||
real topographic data. The latter is the last part of this project.
|
||||
</p>
|
||||
<h3 id="description-of-two-dimensional-function" class="anchor">Description of two-dimensional function </h3>
|
||||
|
||||
<p>We will first study how to fit polynomials to a specific
|
||||
two-dimensional function called <a href="http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf" target="_self">Franke's
|
||||
function</a>. This
|
||||
is a function which has been widely used when testing various
|
||||
interpolation and fitting algorithms. Furthermore, after having
|
||||
established the model and the method, we will employ resamling
|
||||
techniques such as cross-validation and/or bootstrap in order to perform a
|
||||
proper assessment of our models. We will also study in detail the
|
||||
so-called Bias-Variance trade off.
|
||||
</p>
|
||||
|
||||
<p>The Franke function, which is a weighted sum of four exponentials reads as follows</p>
|
||||
$$
|
||||
\begin{align*}
|
||||
f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\
|
||||
&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }.
|
||||
\end{align*}
|
||||
$$
|
||||
|
||||
<p>The function will be defined for \( x,y\in [0,1] \). Our first step will
|
||||
be to perform an OLS regression analysis of this function, trying out
|
||||
a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y,
|
||||
x^2, y^2, xy, \dots] \). We will also include bootstrap first as a
|
||||
resampling technique. After that we will include the cross-validation
|
||||
technique. As discussed in the lectures for weeks 35 and 36,, we can
|
||||
use a uniform distribution to set up the arrays of values for \( x \) and
|
||||
\( y \), or as in the example below just a set of fixed values for \( x \) and
|
||||
\( y \) with a given step size. We will fit a function (for example a
|
||||
polynomial) of \( x \) and \( y \). Thereafter we will repeat much of the
|
||||
same procedure using the Ridge and Lasso regression methods,
|
||||
introducing thus a dependence on the bias (penalty) \( \lambda \).
|
||||
</p>
|
||||
|
||||
<p>Finally we are going to use (real) digital terrain data and try to
|
||||
reproduce these data using the same methods. We will also try to go
|
||||
beyond the second-order polynomials metioned above and explore
|
||||
which polynomial fits the data best.
|
||||
</p>
|
||||
|
||||
<p>The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)</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">from</span> <span style="color: #0000FF; font-weight: bold">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> Axes3D
|
||||
<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">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib.ticker</span> <span style="color: #008000; font-weight: bold">import</span> LinearLocator, FormatStrFormatter
|
||||
<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">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
|
||||
|
||||
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
|
||||
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Make data.</span>
|
||||
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0.05</span>)
|
||||
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0.05</span>)
|
||||
x, y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(x,y)
|
||||
|
||||
|
||||
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">FrankeFunction</span>(x,y):
|
||||
term1 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">0.25*</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>) <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>))
|
||||
term2 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>((<span style="color: #666666">9*</span>x<span style="color: #666666">+1</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">/49.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.1*</span>(<span style="color: #666666">9*</span>y<span style="color: #666666">+1</span>))
|
||||
term3 <span style="color: #666666">=</span> <span style="color: #666666">0.5*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-7</span>)<span style="color: #666666">**2/4.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-3</span>)<span style="color: #666666">**2</span>))
|
||||
term4 <span style="color: #666666">=</span> <span style="color: #666666">-0.2*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-4</span>)<span style="color: #666666">**2</span> <span style="color: #666666">-</span> (<span style="color: #666666">9*</span>y<span style="color: #666666">-7</span>)<span style="color: #666666">**2</span>)
|
||||
<span style="color: #008000; font-weight: bold">return</span> term1 <span style="color: #666666">+</span> term2 <span style="color: #666666">+</span> term3 <span style="color: #666666">+</span> term4
|
||||
|
||||
|
||||
z <span style="color: #666666">=</span> FrankeFunction(x, y)
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Plot the surface.</span>
|
||||
surf <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(x, y, z, cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>coolwarm,
|
||||
linewidth<span style="color: #666666">=0</span>, antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Customize the z axis.</span>
|
||||
ax<span style="color: #666666">.</span>set_zlim(<span style="color: #666666">-0.10</span>, <span style="color: #666666">1.40</span>)
|
||||
ax<span style="color: #666666">.</span>zaxis<span style="color: #666666">.</span>set_major_locator(LinearLocator(<span style="color: #666666">10</span>))
|
||||
ax<span style="color: #666666">.</span>zaxis<span style="color: #666666">.</span>set_major_formatter(FormatStrFormatter(<span style="color: #BA2121">'</span><span style="color: #BB6688; font-weight: bold">%.02f</span><span style="color: #BA2121">'</span>))
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Add a color bar which maps values to colors.</span>
|
||||
fig<span style="color: #666666">.</span>colorbar(surf, shrink<span style="color: #666666">=0.5</span>, aspect<span style="color: #666666">=5</span>)
|
||||
|
||||
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>
|
||||
<h3 id="part-a-paper-and-pencil-part-also-as-weekly-exercise-for-week-36" class="anchor">Part a): Paper and pencil part (also as weekly exercise for week 36) </h3>
|
||||
|
||||
<p>This exercise deals with various mean values and variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of <a href="https://www.springer.com/gp/book/9780387848570" target="_self">Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer</a>).</p>
|
||||
|
||||
<p>The assumption we have made is
|
||||
that there exists a continuous function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim N(0, \sigma^2) \)
|
||||
which describes our data
|
||||
</p>
|
||||
$$
|
||||
\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
|
||||
$$
|
||||
|
||||
<p>We then approximate this function \( f(\boldsymbol{x}) \) with our model \( \boldsymbol{\tilde{y}} \) from the solution of the linear regression equations (ordinary least squares OLS), that is our
|
||||
function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we minimized \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), with
|
||||
</p>
|
||||
$$
|
||||
\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
|
||||
$$
|
||||
|
||||
<p>The matrix \( \boldsymbol{X} \) is the so-called design or feature matrix. </p>
|
||||
|
||||
<p>Show that the expectation value of \( \boldsymbol{y} \) for a given element \( i \) </p>
|
||||
$$
|
||||
\mathbb{E}(y_i) =\sum_{j}x_{ij} \beta_j=\mathbf{X}_{i, \ast} \, \boldsymbol{\beta},
|
||||
$$
|
||||
|
||||
<p>and that
|
||||
its variance is
|
||||
</p>
|
||||
$$
|
||||
\mbox{Var}(y_i) = \sigma^2.
|
||||
$$
|
||||
|
||||
<p>Hence, \( y_i \sim 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 \).
|
||||
</p>
|
||||
|
||||
<p>With the OLS expressions for the optimal parameters \( \boldsymbol{\hat{\beta}} \) show that</p>
|
||||
$$
|
||||
\mathbb{E}(\boldsymbol{\hat{\beta}}) = \boldsymbol{\beta}.
|
||||
$$
|
||||
|
||||
<p>Show finally that the variance of \( \boldsymbol{\beta} \) is</p>
|
||||
$$
|
||||
\mbox{Var}(\boldsymbol{\hat{\beta}}) = \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}.
|
||||
$$
|
||||
|
||||
<p>We can use the last expression when we define a so-called confidence interval for the parameters \( \beta \). .
|
||||
A given parameter \( \beta_j \) is given by the diagonal matrix element of the above matrix.
|
||||
</p>
|
||||
<h3 id="part-b-ordinary-least-square-ols-on-the-franke-function" class="anchor">Part b) : Ordinary Least Square (OLS) on the Franke function </h3>
|
||||
|
||||
<p>We will generate our own dataset for a function
|
||||
\( \mathrm{FrankeFunction}(x,y) \) with \( x,y \in [0,1] \). The function
|
||||
\( f(x,y) \) is the Franke function. You should explore also the addition
|
||||
of an added stochastic noise to this function using the normal
|
||||
distribution \( N(0,1) \).
|
||||
</p>
|
||||
|
||||
<p><em>Write your own code</em> (using either a matrix inversion or a singular
|
||||
value decomposition from e.g., <b>numpy</b> ) and perform a standard <b>ordinary least square regression</b>
|
||||
analysis using polynomials in \( x \) and \( y \) up to fifth order.
|
||||
</p>
|
||||
|
||||
<p>Evaluate the mean Squared error (MSE)</p>
|
||||
|
||||
$$ MSE(\boldsymbol{y},\tilde{\boldsymbol{y}}) = \frac{1}{n}
|
||||
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
|
||||
$$
|
||||
|
||||
<p>and the \( R^2 \) score function. If \( \tilde{\boldsymbol{y}}_i \) is the predicted
|
||||
value of the \( i-th \) sample and \( y_i \) is the corresponding true value,
|
||||
then the score \( R^2 \) is defined as
|
||||
</p>
|
||||
|
||||
$$
|
||||
R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
|
||||
$$
|
||||
|
||||
<p>where we have defined the mean value of \( \boldsymbol{y} \) as</p>
|
||||
|
||||
$$
|
||||
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
|
||||
$$
|
||||
|
||||
<p>Plot the resulting scores (MSE and R$^2$) as functions of the polynomial degree (here up to polymial degree five).
|
||||
Plot also the parameters \( \beta \) as you increase the order of the polynomial. Comment your results.
|
||||
</p>
|
||||
|
||||
<p>Your code has to include a scaling/centering of the data (for example by
|
||||
subtracting the mean value), and
|
||||
a split of the data in training and test data. For this exercise you can
|
||||
either write your own code or use for example the function for
|
||||
splitting training data provided by the library <b>Scikit-Learn</b> (make
|
||||
sure you have installed it). This function is called
|
||||
\( train\_test\_split \). <b>You should present a critical discussion of why and how you have scaled or not scaled the data</b>.
|
||||
</p>
|
||||
|
||||
<p>It is normal in essentially all Machine Learning studies to split the
|
||||
data in a training set and a test set (eventually also an additional
|
||||
validation set). There
|
||||
is no explicit recipe for how much data should be included as training
|
||||
data and say test data. An accepted rule of thumb is to use
|
||||
approximately \( 2/3 \) to \( 4/5 \) of the data as training data.
|
||||
</p>
|
||||
|
||||
<p>You can easily reuse the solutions to your exercises from week 35 and week 36.
|
||||
See also the lecture slides from week 35 and week 36.
|
||||
</p>
|
||||
<h3 id="part-c-bias-variance-trade-off-and-resampling-techniques" class="anchor">Part c): Bias-variance trade-off and resampling techniques </h3>
|
||||
|
||||
<p>Our aim here is to study the bias-variance trade-off by implementing the <b>bootstrap</b> resampling technique.</p>
|
||||
|
||||
<p>With a code which does OLS and includes resampling techniques,
|
||||
we will now discuss the bias-variance trade-off in the context of
|
||||
continuous predictions such as regression. However, many of the
|
||||
intuitions and ideas discussed here also carry over to classification
|
||||
tasks and basically all Machine Learning algorithms.
|
||||
</p>
|
||||
|
||||
<p>Before you perform an analysis of the bias-variance trade-off on your test data, make
|
||||
first a figure similar to Fig. 2.11 of Hastie, Tibshirani, and
|
||||
Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to
|
||||
indicate possible regions of low/high bias and variance. You will most likely not get an
|
||||
equally smooth curve!
|
||||
</p>
|
||||
|
||||
<p>With this result we move on to the bias-variance trade-off analysis.</p>
|
||||
|
||||
<p>Consider a
|
||||
dataset \( \mathcal{L} \) consisting of the data
|
||||
\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \).
|
||||
</p>
|
||||
|
||||
<p>As in part a), we assume that the true data is generated from a noisy model</p>
|
||||
|
||||
$$
|
||||
\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}.
|
||||
$$
|
||||
|
||||
<p>Here \( \epsilon \) is normally distributed with mean zero and standard
|
||||
deviation \( \sigma^2 \).
|
||||
</p>
|
||||
|
||||
<p>In our derivation of the ordinary least squares method we defined then
|
||||
an approximation to the function \( f \) in terms of the parameters
|
||||
\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model,
|
||||
that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \).
|
||||
</p>
|
||||
|
||||
<p>The parameters \( \boldsymbol{\beta} \) are in turn found by optimizing the means
|
||||
squared error via the so-called cost function
|
||||
</p>
|
||||
|
||||
$$
|
||||
C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
|
||||
$$
|
||||
|
||||
<p>Here the expected value \( \mathbb{E} \) is the sample value. </p>
|
||||
|
||||
<p>Show that you can rewrite this in terms of a term which contains the variance of the model itself (the so-called variance term), a
|
||||
term which measures the deviation from the true data and the mean value of the model (the bias term) and finally the variance of the noise.
|
||||
That is, show that
|
||||
</p>
|
||||
$$
|
||||
\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=(\mathrm{Bias}[\tilde{y}])^2+\mathrm{var}[\tilde{f}]+\sigma^2,
|
||||
$$
|
||||
|
||||
<p>with </p>
|
||||
$$
|
||||
(\mathrm{Bias}[\tilde{y}])^2=\left(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]\right)^2,
|
||||
$$
|
||||
|
||||
<p>and </p>
|
||||
$$
|
||||
\mathrm{var}[\tilde{f}]=\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2.
|
||||
$$
|
||||
|
||||
<p>The answer to this exercise should be included in the theory part of the report.
|
||||
Explain what the terms mean and discuss their interpretations.
|
||||
</p>
|
||||
|
||||
<p>Perform then a bias-variance analysis of the Franke function by
|
||||
studying the MSE value as function of the complexity of your model.
|
||||
</p>
|
||||
|
||||
<p>Discuss the bias and variance trade-off as function
|
||||
of your model complexity (the degree of the polynomial) and the number
|
||||
of data points, and possibly also your training and test data using the <b>bootstrap</b> resampling method.
|
||||
You can follow the code example in the jupyter-book at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff</tt></a>.
|
||||
</p>
|
||||
<h3 id="part-d-cross-validation-as-resampling-techniques-adding-more-complexity" class="anchor">Part d): Cross-validation as resampling techniques, adding more complexity </h3>
|
||||
|
||||
<p>The aim here is to write your own code for another widely popular
|
||||
resampling technique, the so-called cross-validation method. Again,
|
||||
before you start with cross-validation approach, you should scale your
|
||||
data if you think this is needed.
|
||||
</p>
|
||||
|
||||
<p>Implement the \( k \)-fold cross-validation algorithm (write your own
|
||||
code) and evaluate again the MSE function resulting
|
||||
from the test folds. You can compare your own code with that from
|
||||
<b>Scikit-Learn</b> if needed.
|
||||
</p>
|
||||
|
||||
<p>Compare the MSE you get from your cross-validation code with the one
|
||||
you got from your <b>bootstrap</b> code. Comment your results. Try \( 5-10 \)
|
||||
folds. You can also compare your own cross-validation code with the
|
||||
one provided by <b>Scikit-Learn</b>.
|
||||
</p>
|
||||
<h3 id="part-e-ridge-regression-on-the-franke-function-with-resampling" class="anchor">Part e): Ridge Regression on the Franke function with resampling </h3>
|
||||
|
||||
<p>Write your own code for the Ridge method, either using matrix
|
||||
inversion or the singular value decomposition as done in the previous
|
||||
exercise. Perform the same bootstrap analysis as in the
|
||||
part c) (for the same polynomials) and the cross-validation in part d) but now for different values of \( \lambda \). Compare and
|
||||
analyze your results with those obtained in parts b-d). Study the
|
||||
dependence on \( \lambda \).
|
||||
</p>
|
||||
|
||||
<p>Study also the bias-variance trade-off as function of various values of
|
||||
the parameter \( \lambda \). For the bias-variance trade-off, use the <b>bootstrap</b> resampling method. Comment your results.
|
||||
</p>
|
||||
<h3 id="part-f-lasso-regression-on-the-franke-function-with-resampling" class="anchor">Part f): Lasso Regression on the Franke function with resampling </h3>
|
||||
|
||||
<p>This exercise is essentially a repeat of the previous two ones, but now
|
||||
with Lasso regression. Write either your own code (difficult and optional) or, in this case,
|
||||
you can also use the functionalities of <b>Scikit-Learn</b> (recommended).
|
||||
Give a
|
||||
critical discussion of the three methods and a judgement of which
|
||||
model fits the data best. Perform here as well an analysis of the bias-variance trade-off using the <b>bootstrap</b> resampling technique and an analysis of the mean squared error using cross-validation.
|
||||
</p>
|
||||
<h3 id="part-g-analysis-of-real-data" class="anchor">Part g): Analysis of real data </h3>
|
||||
|
||||
<p>With our codes functioning and having been tested properly on a
|
||||
simpler function we are now ready to look at real data. We will
|
||||
essentially repeat in this exercise what was done in exercises 1-5. However, we
|
||||
need first to download the data and prepare properly the inputs to our
|
||||
codes. We are going to download digital terrain data from the website
|
||||
<a href="https://earthexplorer.usgs.gov/" target="_self"><tt>https://earthexplorer.usgs.gov/</tt></a>,
|
||||
</p>
|
||||
|
||||
<p>Or, if you prefer, we have placed selected datafiles at <a href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles" target="_self"><tt>https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles</tt></a></p>
|
||||
|
||||
<p>In order to obtain data for a specific region, you need to register as
|
||||
a user (free) at this website and then decide upon which area you want
|
||||
to fetch the digital terrain data from. In order to be able to read
|
||||
the data properly, you need to specify that the format should be <b>SRTM
|
||||
Arc-Second Global</b> and download the data as a <b>GeoTIF</b> file. The
|
||||
files are then stored in <em>tif</em> format which can be imported into a
|
||||
Python program using
|
||||
</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%;">scipy<span style="color: #666666">.</span>misc<span style="color: #666666">.</span>imread
|
||||
</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>Here is a simple part of a Python code which reads and plots the data
|
||||
from such files
|
||||
</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">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">from</span> <span style="color: #0000FF; font-weight: bold">imageio</span> <span style="color: #008000; font-weight: bold">import</span> imread
|
||||
<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">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> Axes3D
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Load the terrain</span>
|
||||
terrain1 <span style="color: #666666">=</span> imread(<span style="color: #BA2121">'SRTM_data_Norway_1.tif'</span>)
|
||||
<span style="color: #408080; font-style: italic"># Show the terrain</span>
|
||||
plt<span style="color: #666666">.</span>figure()
|
||||
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">'Terrain over Norway 1'</span>)
|
||||
plt<span style="color: #666666">.</span>imshow(terrain1, cmap<span style="color: #666666">=</span><span style="color: #BA2121">'gray'</span>)
|
||||
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'X'</span>)
|
||||
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'Y'</span>)
|
||||
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>If you should have problems in downloading the digital terrain data,
|
||||
we provide two examples under the data folder of project 1. One is
|
||||
from a region close to Stavanger in Norway and the other Møsvatn
|
||||
Austfjell, again in Norway.
|
||||
Feel free to produce your own terrain data.
|
||||
</p>
|
||||
|
||||
<p>Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example <a href="https://www.kaggle.com/datasets" target="_self">kaggle.com</a> for examples.</p>
|
||||
|
||||
<p>Our final part deals with the parameterization of your digital terrain
|
||||
data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial
|
||||
approximation and cross-validation as resampling technique to evaluate which
|
||||
model fits the data best.
|
||||
</p>
|
||||
|
||||
<p>At the end, you should present a critical evaluation of your results
|
||||
and discuss the applicability of these regression methods to the type
|
||||
of data presented here (either the terrain data we propose or other data sets).
|
||||
</p>
|
||||
<h2 id="background-literature" class="anchor">Background literature </h2>
|
||||
|
||||
<ol>
|
||||
<li> For a discussion and derivation of the variances and mean squared errors using linear regression, see the <a href="https://arxiv.org/abs/1509.09169" target="_self">Lecture notes on ridge regression by Wessel N. van Wieringen</a></li>
|
||||
<li> The textbook of <a href="https://www.springer.com/gp/book/9780387848570" target="_self">Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer</a>, chapters 3 and 7 are the most relevant ones for the analysis here.</li>
|
||||
</ol>
|
||||
<h2 id="introduction-to-numerical-projects" class="anchor">Introduction to numerical projects </h2>
|
||||
|
||||
<p>Here follows a brief recipe and recommendation on how to answer the various questions when preparing your answers. </p>
|
||||
|
||||
<ul>
|
||||
<li> Give a short description of the nature of the problem and the eventual numerical methods you have used.</li>
|
||||
<li> Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.</li>
|
||||
<li> Include the source code of your program. Comment your program properly. You should have the code at your GitHub/GitLab link. You can also place the code in an appendix of your report.</li>
|
||||
<li> If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.</li>
|
||||
<li> Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.</li>
|
||||
<li> Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.</li>
|
||||
<li> Try to give an interpretation of you results in your answers to the problems.</li>
|
||||
<li> Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.</li>
|
||||
<li> Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.</li>
|
||||
</ul>
|
||||
<h2 id="format-for-electronic-delivery-of-report-and-programs" class="anchor">Format for electronic delivery of report and programs </h2>
|
||||
|
||||
<p>The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008, Julia or Python. The following prescription should be followed when preparing the report:</p>
|
||||
|
||||
@@ -8,7 +8,8 @@ doconce format html Project1.do.txt --html_style=bootstrap --pygments_html_style
|
||||
<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" />
|
||||
<title></title>
|
||||
<meta name="description" content="Project 1 on Machine Learning, deadline October 7, 2022">
|
||||
<title>Project 1 on Machine Learning, deadline October 7, 2022</title>
|
||||
<!-- Bootstrap style: bootstrap -->
|
||||
<!-- doconce format html Project1.do.txt --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=Project1-bs -->
|
||||
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
|
||||
@@ -35,7 +36,52 @@ doconce format html Project1.do.txt --html_style=bootstrap --pygments_html_style
|
||||
|
||||
<!-- tocinfo
|
||||
{'highest level': 2,
|
||||
'sections': [('Format for electronic delivery of report and programs',
|
||||
'sections': [('Regression analysis and resampling methods',
|
||||
2,
|
||||
None,
|
||||
'regression-analysis-and-resampling-methods'),
|
||||
('Description of two-dimensional function',
|
||||
3,
|
||||
None,
|
||||
'description-of-two-dimensional-function'),
|
||||
('Part a): Paper and pencil part (also as weekly exercise for '
|
||||
'week 36)',
|
||||
3,
|
||||
None,
|
||||
'part-a-paper-and-pencil-part-also-as-weekly-exercise-for-week-36'),
|
||||
('Part b) : Ordinary Least Square (OLS) on the Franke function',
|
||||
3,
|
||||
None,
|
||||
'part-b-ordinary-least-square-ols-on-the-franke-function'),
|
||||
('Part c): Bias-variance trade-off and resampling techniques',
|
||||
3,
|
||||
None,
|
||||
'part-c-bias-variance-trade-off-and-resampling-techniques'),
|
||||
('Part d): Cross-validation as resampling techniques, adding '
|
||||
'more complexity',
|
||||
3,
|
||||
None,
|
||||
'part-d-cross-validation-as-resampling-techniques-adding-more-complexity'),
|
||||
('Part e): Ridge Regression on the Franke function with '
|
||||
'resampling',
|
||||
3,
|
||||
None,
|
||||
'part-e-ridge-regression-on-the-franke-function-with-resampling'),
|
||||
('Part f): Lasso Regression on the Franke function with '
|
||||
'resampling',
|
||||
3,
|
||||
None,
|
||||
'part-f-lasso-regression-on-the-franke-function-with-resampling'),
|
||||
('Part g): Analysis of real data',
|
||||
3,
|
||||
None,
|
||||
'part-g-analysis-of-real-data'),
|
||||
('Background literature', 2, None, 'background-literature'),
|
||||
('Introduction to numerical projects',
|
||||
2,
|
||||
None,
|
||||
'introduction-to-numerical-projects'),
|
||||
('Format for electronic delivery of report and programs',
|
||||
2,
|
||||
None,
|
||||
'format-for-electronic-delivery-of-report-and-programs'),
|
||||
@@ -46,10 +92,571 @@ doconce format html Project1.do.txt --html_style=bootstrap --pygments_html_style
|
||||
end of tocinfo -->
|
||||
|
||||
<body>
|
||||
|
||||
|
||||
|
||||
<script type="text/x-mathjax-config">
|
||||
MathJax.Hub.Config({
|
||||
TeX: {
|
||||
equationNumbers: { autoNumber: "none" },
|
||||
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>
|
||||
|
||||
|
||||
<!-- Bootstrap navigation bar -->
|
||||
<div class="navbar navbar-default navbar-fixed-top">
|
||||
<div class="navbar-header">
|
||||
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">
|
||||
<span class="icon-bar"></span>
|
||||
<span class="icon-bar"></span>
|
||||
<span class="icon-bar"></span>
|
||||
</button>
|
||||
<a class="navbar-brand" href="Project1-bs.html">Project 1 on Machine Learning, deadline October 7, 2022</a>
|
||||
</div>
|
||||
<div class="navbar-collapse collapse navbar-responsive-collapse">
|
||||
<ul class="nav navbar-nav navbar-right">
|
||||
<li class="dropdown">
|
||||
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
|
||||
<ul class="dropdown-menu">
|
||||
<!-- navigation toc: --> <li><a href="#regression-analysis-and-resampling-methods" style="font-size: 80%;"><b>Regression analysis and resampling methods</b></a></li>
|
||||
<!-- navigation toc: --> <li><a href="#description-of-two-dimensional-function" style="font-size: 80%;"> Description of two-dimensional function</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-a-paper-and-pencil-part-also-as-weekly-exercise-for-week-36" style="font-size: 80%;"> Part a): Paper and pencil part (also as weekly exercise for week 36)</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-b-ordinary-least-square-ols-on-the-franke-function" style="font-size: 80%;"> Part b) : Ordinary Least Square (OLS) on the Franke function</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-c-bias-variance-trade-off-and-resampling-techniques" style="font-size: 80%;"> Part c): Bias-variance trade-off and resampling techniques</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-d-cross-validation-as-resampling-techniques-adding-more-complexity" style="font-size: 80%;"> Part d): Cross-validation as resampling techniques, adding more complexity</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-e-ridge-regression-on-the-franke-function-with-resampling" style="font-size: 80%;"> Part e): Ridge Regression on the Franke function with resampling</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-f-lasso-regression-on-the-franke-function-with-resampling" style="font-size: 80%;"> Part f): Lasso Regression on the Franke function with resampling</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#part-g-analysis-of-real-data" style="font-size: 80%;"> Part g): Analysis of real data</a></li>
|
||||
<!-- navigation toc: --> <li><a href="#background-literature" style="font-size: 80%;"><b>Background literature</b></a></li>
|
||||
<!-- navigation toc: --> <li><a href="#introduction-to-numerical-projects" style="font-size: 80%;"><b>Introduction to numerical projects</b></a></li>
|
||||
<!-- navigation toc: --> <li><a href="#format-for-electronic-delivery-of-report-and-programs" style="font-size: 80%;"><b>Format for electronic delivery of report and programs</b></a></li>
|
||||
<!-- navigation toc: --> <li><a href="#software-and-needed-installations" style="font-size: 80%;"><b>Software and needed installations</b></a></li>
|
||||
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div> <!-- end of navigation bar -->
|
||||
<div class="container">
|
||||
<p> </p><p> </p><p> </p> <!-- add vertical space -->
|
||||
<a name="part0000"></a>
|
||||
<!-- ------------------- main content ---------------------- -->
|
||||
<div class="jumbotron">
|
||||
<center>
|
||||
<h1>Project 1 on Machine Learning, deadline October 7, 2022</h1>
|
||||
</center> <!-- document title -->
|
||||
|
||||
<!-- author(s): <a href="http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" target="_self">Data Analysis and Machine Learning FYS-STK3155/FYS4155</a> -->
|
||||
<center>
|
||||
<b><a href="http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" target="_self">Data Analysis and Machine Learning FYS-STK3155/FYS4155</a></b>
|
||||
</center>
|
||||
<!-- institution -->
|
||||
<center>
|
||||
<b>University of Oslo, Norway</b>
|
||||
</center>
|
||||
<br>
|
||||
<center>
|
||||
<h4>Sep 7, 2022</h4>
|
||||
</center> <!-- date -->
|
||||
<br>
|
||||
|
||||
|
||||
</div> <!-- end jumbotron -->
|
||||
<h2 id="regression-analysis-and-resampling-methods" class="anchor">Regression analysis and resampling methods </h2>
|
||||
|
||||
<p>The main aim of this project is to study in more detail various
|
||||
regression methods, including the Ordinary Least Squares (OLS) method.
|
||||
In addition to the scientific part, in this course we want also to
|
||||
give you an experience in writing scientific reports. The format for
|
||||
the delivery of your answers is namely that of a scientific report. At
|
||||
for example
|
||||
<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md" target="_self"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md</tt></a>
|
||||
we detail how to write a report. Furthermore, at
|
||||
<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/" target="_self"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/</tt></a>
|
||||
you can find examples of previous reports. How to write reports will
|
||||
also be discussed during lectures and at the various lab sessions.
|
||||
</p>
|
||||
|
||||
<p><b>A small recommendation when developing the codes here</b>. Instead of
|
||||
jumping on to the two-dimensional function described below, we
|
||||
recommend to do the code development and testing with a simpler
|
||||
one-dimensional function, similar to those discussed in the exercises
|
||||
of week 35. A simple test, as discussed during the lectures the first
|
||||
two weeks is to set the design matrix equal to the identity
|
||||
matrix. Then your model should give a mean square error which is exactly equal to zero.
|
||||
When you are sure that your codes function well, you can then replace
|
||||
the one-dimensional test function with the two-dimensional <b>Franke</b> function
|
||||
discussed here.
|
||||
</p>
|
||||
|
||||
<p>The Franke function serves as a stepping stone towards the analysis of
|
||||
real topographic data. The latter is the last part of this project.
|
||||
</p>
|
||||
<h3 id="description-of-two-dimensional-function" class="anchor">Description of two-dimensional function </h3>
|
||||
|
||||
<p>We will first study how to fit polynomials to a specific
|
||||
two-dimensional function called <a href="http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf" target="_self">Franke's
|
||||
function</a>. This
|
||||
is a function which has been widely used when testing various
|
||||
interpolation and fitting algorithms. Furthermore, after having
|
||||
established the model and the method, we will employ resamling
|
||||
techniques such as cross-validation and/or bootstrap in order to perform a
|
||||
proper assessment of our models. We will also study in detail the
|
||||
so-called Bias-Variance trade off.
|
||||
</p>
|
||||
|
||||
<p>The Franke function, which is a weighted sum of four exponentials reads as follows</p>
|
||||
$$
|
||||
\begin{align*}
|
||||
f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\
|
||||
&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }.
|
||||
\end{align*}
|
||||
$$
|
||||
|
||||
<p>The function will be defined for \( x,y\in [0,1] \). Our first step will
|
||||
be to perform an OLS regression analysis of this function, trying out
|
||||
a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y,
|
||||
x^2, y^2, xy, \dots] \). We will also include bootstrap first as a
|
||||
resampling technique. After that we will include the cross-validation
|
||||
technique. As discussed in the lectures for weeks 35 and 36,, we can
|
||||
use a uniform distribution to set up the arrays of values for \( x \) and
|
||||
\( y \), or as in the example below just a set of fixed values for \( x \) and
|
||||
\( y \) with a given step size. We will fit a function (for example a
|
||||
polynomial) of \( x \) and \( y \). Thereafter we will repeat much of the
|
||||
same procedure using the Ridge and Lasso regression methods,
|
||||
introducing thus a dependence on the bias (penalty) \( \lambda \).
|
||||
</p>
|
||||
|
||||
<p>Finally we are going to use (real) digital terrain data and try to
|
||||
reproduce these data using the same methods. We will also try to go
|
||||
beyond the second-order polynomials metioned above and explore
|
||||
which polynomial fits the data best.
|
||||
</p>
|
||||
|
||||
<p>The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)</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">from</span> <span style="color: #0000FF; font-weight: bold">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> Axes3D
|
||||
<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">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib.ticker</span> <span style="color: #008000; font-weight: bold">import</span> LinearLocator, FormatStrFormatter
|
||||
<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">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
|
||||
|
||||
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
|
||||
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Make data.</span>
|
||||
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0.05</span>)
|
||||
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0.05</span>)
|
||||
x, y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(x,y)
|
||||
|
||||
|
||||
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">FrankeFunction</span>(x,y):
|
||||
term1 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">0.25*</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>) <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>))
|
||||
term2 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>((<span style="color: #666666">9*</span>x<span style="color: #666666">+1</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">/49.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.1*</span>(<span style="color: #666666">9*</span>y<span style="color: #666666">+1</span>))
|
||||
term3 <span style="color: #666666">=</span> <span style="color: #666666">0.5*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-7</span>)<span style="color: #666666">**2/4.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-3</span>)<span style="color: #666666">**2</span>))
|
||||
term4 <span style="color: #666666">=</span> <span style="color: #666666">-0.2*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-4</span>)<span style="color: #666666">**2</span> <span style="color: #666666">-</span> (<span style="color: #666666">9*</span>y<span style="color: #666666">-7</span>)<span style="color: #666666">**2</span>)
|
||||
<span style="color: #008000; font-weight: bold">return</span> term1 <span style="color: #666666">+</span> term2 <span style="color: #666666">+</span> term3 <span style="color: #666666">+</span> term4
|
||||
|
||||
|
||||
z <span style="color: #666666">=</span> FrankeFunction(x, y)
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Plot the surface.</span>
|
||||
surf <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(x, y, z, cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>coolwarm,
|
||||
linewidth<span style="color: #666666">=0</span>, antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Customize the z axis.</span>
|
||||
ax<span style="color: #666666">.</span>set_zlim(<span style="color: #666666">-0.10</span>, <span style="color: #666666">1.40</span>)
|
||||
ax<span style="color: #666666">.</span>zaxis<span style="color: #666666">.</span>set_major_locator(LinearLocator(<span style="color: #666666">10</span>))
|
||||
ax<span style="color: #666666">.</span>zaxis<span style="color: #666666">.</span>set_major_formatter(FormatStrFormatter(<span style="color: #BA2121">'</span><span style="color: #BB6688; font-weight: bold">%.02f</span><span style="color: #BA2121">'</span>))
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Add a color bar which maps values to colors.</span>
|
||||
fig<span style="color: #666666">.</span>colorbar(surf, shrink<span style="color: #666666">=0.5</span>, aspect<span style="color: #666666">=5</span>)
|
||||
|
||||
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>
|
||||
<h3 id="part-a-paper-and-pencil-part-also-as-weekly-exercise-for-week-36" class="anchor">Part a): Paper and pencil part (also as weekly exercise for week 36) </h3>
|
||||
|
||||
<p>This exercise deals with various mean values and variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of <a href="https://www.springer.com/gp/book/9780387848570" target="_self">Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer</a>).</p>
|
||||
|
||||
<p>The assumption we have made is
|
||||
that there exists a continuous function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim N(0, \sigma^2) \)
|
||||
which describes our data
|
||||
</p>
|
||||
$$
|
||||
\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
|
||||
$$
|
||||
|
||||
<p>We then approximate this function \( f(\boldsymbol{x}) \) with our model \( \boldsymbol{\tilde{y}} \) from the solution of the linear regression equations (ordinary least squares OLS), that is our
|
||||
function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we minimized \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), with
|
||||
</p>
|
||||
$$
|
||||
\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
|
||||
$$
|
||||
|
||||
<p>The matrix \( \boldsymbol{X} \) is the so-called design or feature matrix. </p>
|
||||
|
||||
<p>Show that the expectation value of \( \boldsymbol{y} \) for a given element \( i \) </p>
|
||||
$$
|
||||
\mathbb{E}(y_i) =\sum_{j}x_{ij} \beta_j=\mathbf{X}_{i, \ast} \, \boldsymbol{\beta},
|
||||
$$
|
||||
|
||||
<p>and that
|
||||
its variance is
|
||||
</p>
|
||||
$$
|
||||
\mbox{Var}(y_i) = \sigma^2.
|
||||
$$
|
||||
|
||||
<p>Hence, \( y_i \sim 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 \).
|
||||
</p>
|
||||
|
||||
<p>With the OLS expressions for the optimal parameters \( \boldsymbol{\hat{\beta}} \) show that</p>
|
||||
$$
|
||||
\mathbb{E}(\boldsymbol{\hat{\beta}}) = \boldsymbol{\beta}.
|
||||
$$
|
||||
|
||||
<p>Show finally that the variance of \( \boldsymbol{\beta} \) is</p>
|
||||
$$
|
||||
\mbox{Var}(\boldsymbol{\hat{\beta}}) = \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}.
|
||||
$$
|
||||
|
||||
<p>We can use the last expression when we define a so-called confidence interval for the parameters \( \beta \). .
|
||||
A given parameter \( \beta_j \) is given by the diagonal matrix element of the above matrix.
|
||||
</p>
|
||||
<h3 id="part-b-ordinary-least-square-ols-on-the-franke-function" class="anchor">Part b) : Ordinary Least Square (OLS) on the Franke function </h3>
|
||||
|
||||
<p>We will generate our own dataset for a function
|
||||
\( \mathrm{FrankeFunction}(x,y) \) with \( x,y \in [0,1] \). The function
|
||||
\( f(x,y) \) is the Franke function. You should explore also the addition
|
||||
of an added stochastic noise to this function using the normal
|
||||
distribution \( N(0,1) \).
|
||||
</p>
|
||||
|
||||
<p><em>Write your own code</em> (using either a matrix inversion or a singular
|
||||
value decomposition from e.g., <b>numpy</b> ) and perform a standard <b>ordinary least square regression</b>
|
||||
analysis using polynomials in \( x \) and \( y \) up to fifth order.
|
||||
</p>
|
||||
|
||||
<p>Evaluate the mean Squared error (MSE)</p>
|
||||
|
||||
$$ MSE(\boldsymbol{y},\tilde{\boldsymbol{y}}) = \frac{1}{n}
|
||||
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
|
||||
$$
|
||||
|
||||
<p>and the \( R^2 \) score function. If \( \tilde{\boldsymbol{y}}_i \) is the predicted
|
||||
value of the \( i-th \) sample and \( y_i \) is the corresponding true value,
|
||||
then the score \( R^2 \) is defined as
|
||||
</p>
|
||||
|
||||
$$
|
||||
R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
|
||||
$$
|
||||
|
||||
<p>where we have defined the mean value of \( \boldsymbol{y} \) as</p>
|
||||
|
||||
$$
|
||||
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
|
||||
$$
|
||||
|
||||
<p>Plot the resulting scores (MSE and R$^2$) as functions of the polynomial degree (here up to polymial degree five).
|
||||
Plot also the parameters \( \beta \) as you increase the order of the polynomial. Comment your results.
|
||||
</p>
|
||||
|
||||
<p>Your code has to include a scaling/centering of the data (for example by
|
||||
subtracting the mean value), and
|
||||
a split of the data in training and test data. For this exercise you can
|
||||
either write your own code or use for example the function for
|
||||
splitting training data provided by the library <b>Scikit-Learn</b> (make
|
||||
sure you have installed it). This function is called
|
||||
\( train\_test\_split \). <b>You should present a critical discussion of why and how you have scaled or not scaled the data</b>.
|
||||
</p>
|
||||
|
||||
<p>It is normal in essentially all Machine Learning studies to split the
|
||||
data in a training set and a test set (eventually also an additional
|
||||
validation set). There
|
||||
is no explicit recipe for how much data should be included as training
|
||||
data and say test data. An accepted rule of thumb is to use
|
||||
approximately \( 2/3 \) to \( 4/5 \) of the data as training data.
|
||||
</p>
|
||||
|
||||
<p>You can easily reuse the solutions to your exercises from week 35 and week 36.
|
||||
See also the lecture slides from week 35 and week 36.
|
||||
</p>
|
||||
<h3 id="part-c-bias-variance-trade-off-and-resampling-techniques" class="anchor">Part c): Bias-variance trade-off and resampling techniques </h3>
|
||||
|
||||
<p>Our aim here is to study the bias-variance trade-off by implementing the <b>bootstrap</b> resampling technique.</p>
|
||||
|
||||
<p>With a code which does OLS and includes resampling techniques,
|
||||
we will now discuss the bias-variance trade-off in the context of
|
||||
continuous predictions such as regression. However, many of the
|
||||
intuitions and ideas discussed here also carry over to classification
|
||||
tasks and basically all Machine Learning algorithms.
|
||||
</p>
|
||||
|
||||
<p>Before you perform an analysis of the bias-variance trade-off on your test data, make
|
||||
first a figure similar to Fig. 2.11 of Hastie, Tibshirani, and
|
||||
Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to
|
||||
indicate possible regions of low/high bias and variance. You will most likely not get an
|
||||
equally smooth curve!
|
||||
</p>
|
||||
|
||||
<p>With this result we move on to the bias-variance trade-off analysis.</p>
|
||||
|
||||
<p>Consider a
|
||||
dataset \( \mathcal{L} \) consisting of the data
|
||||
\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \).
|
||||
</p>
|
||||
|
||||
<p>As in part a), we assume that the true data is generated from a noisy model</p>
|
||||
|
||||
$$
|
||||
\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}.
|
||||
$$
|
||||
|
||||
<p>Here \( \epsilon \) is normally distributed with mean zero and standard
|
||||
deviation \( \sigma^2 \).
|
||||
</p>
|
||||
|
||||
<p>In our derivation of the ordinary least squares method we defined then
|
||||
an approximation to the function \( f \) in terms of the parameters
|
||||
\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model,
|
||||
that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \).
|
||||
</p>
|
||||
|
||||
<p>The parameters \( \boldsymbol{\beta} \) are in turn found by optimizing the means
|
||||
squared error via the so-called cost function
|
||||
</p>
|
||||
|
||||
$$
|
||||
C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
|
||||
$$
|
||||
|
||||
<p>Here the expected value \( \mathbb{E} \) is the sample value. </p>
|
||||
|
||||
<p>Show that you can rewrite this in terms of a term which contains the variance of the model itself (the so-called variance term), a
|
||||
term which measures the deviation from the true data and the mean value of the model (the bias term) and finally the variance of the noise.
|
||||
That is, show that
|
||||
</p>
|
||||
$$
|
||||
\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=(\mathrm{Bias}[\tilde{y}])^2+\mathrm{var}[\tilde{f}]+\sigma^2,
|
||||
$$
|
||||
|
||||
<p>with </p>
|
||||
$$
|
||||
(\mathrm{Bias}[\tilde{y}])^2=\left(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]\right)^2,
|
||||
$$
|
||||
|
||||
<p>and </p>
|
||||
$$
|
||||
\mathrm{var}[\tilde{f}]=\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2.
|
||||
$$
|
||||
|
||||
<p>The answer to this exercise should be included in the theory part of the report.
|
||||
Explain what the terms mean and discuss their interpretations.
|
||||
</p>
|
||||
|
||||
<p>Perform then a bias-variance analysis of the Franke function by
|
||||
studying the MSE value as function of the complexity of your model.
|
||||
</p>
|
||||
|
||||
<p>Discuss the bias and variance trade-off as function
|
||||
of your model complexity (the degree of the polynomial) and the number
|
||||
of data points, and possibly also your training and test data using the <b>bootstrap</b> resampling method.
|
||||
You can follow the code example in the jupyter-book at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff</tt></a>.
|
||||
</p>
|
||||
<h3 id="part-d-cross-validation-as-resampling-techniques-adding-more-complexity" class="anchor">Part d): Cross-validation as resampling techniques, adding more complexity </h3>
|
||||
|
||||
<p>The aim here is to write your own code for another widely popular
|
||||
resampling technique, the so-called cross-validation method. Again,
|
||||
before you start with cross-validation approach, you should scale your
|
||||
data if you think this is needed.
|
||||
</p>
|
||||
|
||||
<p>Implement the \( k \)-fold cross-validation algorithm (write your own
|
||||
code) and evaluate again the MSE function resulting
|
||||
from the test folds. You can compare your own code with that from
|
||||
<b>Scikit-Learn</b> if needed.
|
||||
</p>
|
||||
|
||||
<p>Compare the MSE you get from your cross-validation code with the one
|
||||
you got from your <b>bootstrap</b> code. Comment your results. Try \( 5-10 \)
|
||||
folds. You can also compare your own cross-validation code with the
|
||||
one provided by <b>Scikit-Learn</b>.
|
||||
</p>
|
||||
<h3 id="part-e-ridge-regression-on-the-franke-function-with-resampling" class="anchor">Part e): Ridge Regression on the Franke function with resampling </h3>
|
||||
|
||||
<p>Write your own code for the Ridge method, either using matrix
|
||||
inversion or the singular value decomposition as done in the previous
|
||||
exercise. Perform the same bootstrap analysis as in the
|
||||
part c) (for the same polynomials) and the cross-validation in part d) but now for different values of \( \lambda \). Compare and
|
||||
analyze your results with those obtained in parts b-d). Study the
|
||||
dependence on \( \lambda \).
|
||||
</p>
|
||||
|
||||
<p>Study also the bias-variance trade-off as function of various values of
|
||||
the parameter \( \lambda \). For the bias-variance trade-off, use the <b>bootstrap</b> resampling method. Comment your results.
|
||||
</p>
|
||||
<h3 id="part-f-lasso-regression-on-the-franke-function-with-resampling" class="anchor">Part f): Lasso Regression on the Franke function with resampling </h3>
|
||||
|
||||
<p>This exercise is essentially a repeat of the previous two ones, but now
|
||||
with Lasso regression. Write either your own code (difficult and optional) or, in this case,
|
||||
you can also use the functionalities of <b>Scikit-Learn</b> (recommended).
|
||||
Give a
|
||||
critical discussion of the three methods and a judgement of which
|
||||
model fits the data best. Perform here as well an analysis of the bias-variance trade-off using the <b>bootstrap</b> resampling technique and an analysis of the mean squared error using cross-validation.
|
||||
</p>
|
||||
<h3 id="part-g-analysis-of-real-data" class="anchor">Part g): Analysis of real data </h3>
|
||||
|
||||
<p>With our codes functioning and having been tested properly on a
|
||||
simpler function we are now ready to look at real data. We will
|
||||
essentially repeat in this exercise what was done in exercises 1-5. However, we
|
||||
need first to download the data and prepare properly the inputs to our
|
||||
codes. We are going to download digital terrain data from the website
|
||||
<a href="https://earthexplorer.usgs.gov/" target="_self"><tt>https://earthexplorer.usgs.gov/</tt></a>,
|
||||
</p>
|
||||
|
||||
<p>Or, if you prefer, we have placed selected datafiles at <a href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles" target="_self"><tt>https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles</tt></a></p>
|
||||
|
||||
<p>In order to obtain data for a specific region, you need to register as
|
||||
a user (free) at this website and then decide upon which area you want
|
||||
to fetch the digital terrain data from. In order to be able to read
|
||||
the data properly, you need to specify that the format should be <b>SRTM
|
||||
Arc-Second Global</b> and download the data as a <b>GeoTIF</b> file. The
|
||||
files are then stored in <em>tif</em> format which can be imported into a
|
||||
Python program using
|
||||
</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%;">scipy<span style="color: #666666">.</span>misc<span style="color: #666666">.</span>imread
|
||||
</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>Here is a simple part of a Python code which reads and plots the data
|
||||
from such files
|
||||
</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">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">from</span> <span style="color: #0000FF; font-weight: bold">imageio</span> <span style="color: #008000; font-weight: bold">import</span> imread
|
||||
<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">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> Axes3D
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Load the terrain</span>
|
||||
terrain1 <span style="color: #666666">=</span> imread(<span style="color: #BA2121">'SRTM_data_Norway_1.tif'</span>)
|
||||
<span style="color: #408080; font-style: italic"># Show the terrain</span>
|
||||
plt<span style="color: #666666">.</span>figure()
|
||||
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">'Terrain over Norway 1'</span>)
|
||||
plt<span style="color: #666666">.</span>imshow(terrain1, cmap<span style="color: #666666">=</span><span style="color: #BA2121">'gray'</span>)
|
||||
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'X'</span>)
|
||||
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'Y'</span>)
|
||||
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>If you should have problems in downloading the digital terrain data,
|
||||
we provide two examples under the data folder of project 1. One is
|
||||
from a region close to Stavanger in Norway and the other Møsvatn
|
||||
Austfjell, again in Norway.
|
||||
Feel free to produce your own terrain data.
|
||||
</p>
|
||||
|
||||
<p>Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example <a href="https://www.kaggle.com/datasets" target="_self">kaggle.com</a> for examples.</p>
|
||||
|
||||
<p>Our final part deals with the parameterization of your digital terrain
|
||||
data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial
|
||||
approximation and cross-validation as resampling technique to evaluate which
|
||||
model fits the data best.
|
||||
</p>
|
||||
|
||||
<p>At the end, you should present a critical evaluation of your results
|
||||
and discuss the applicability of these regression methods to the type
|
||||
of data presented here (either the terrain data we propose or other data sets).
|
||||
</p>
|
||||
<h2 id="background-literature" class="anchor">Background literature </h2>
|
||||
|
||||
<ol>
|
||||
<li> For a discussion and derivation of the variances and mean squared errors using linear regression, see the <a href="https://arxiv.org/abs/1509.09169" target="_self">Lecture notes on ridge regression by Wessel N. van Wieringen</a></li>
|
||||
<li> The textbook of <a href="https://www.springer.com/gp/book/9780387848570" target="_self">Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer</a>, chapters 3 and 7 are the most relevant ones for the analysis here.</li>
|
||||
</ol>
|
||||
<h2 id="introduction-to-numerical-projects" class="anchor">Introduction to numerical projects </h2>
|
||||
|
||||
<p>Here follows a brief recipe and recommendation on how to answer the various questions when preparing your answers. </p>
|
||||
|
||||
<ul>
|
||||
<li> Give a short description of the nature of the problem and the eventual numerical methods you have used.</li>
|
||||
<li> Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.</li>
|
||||
<li> Include the source code of your program. Comment your program properly. You should have the code at your GitHub/GitLab link. You can also place the code in an appendix of your report.</li>
|
||||
<li> If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.</li>
|
||||
<li> Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.</li>
|
||||
<li> Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.</li>
|
||||
<li> Try to give an interpretation of you results in your answers to the problems.</li>
|
||||
<li> Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.</li>
|
||||
<li> Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.</li>
|
||||
</ul>
|
||||
<h2 id="format-for-electronic-delivery-of-report-and-programs" class="anchor">Format for electronic delivery of report and programs </h2>
|
||||
|
||||
<p>The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008, Julia or Python. The following prescription should be followed when preparing the report:</p>
|
||||
|
||||
@@ -8,7 +8,8 @@ doconce format html Project1.do.txt --pygments_html_style=default --html_style=b
|
||||
<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" />
|
||||
<title></title>
|
||||
<meta name="description" content="Project 1 on Machine Learning, deadline October 7, 2022">
|
||||
<title>Project 1 on Machine Learning, deadline October 7, 2022</title>
|
||||
<style type="text/css">
|
||||
/* bloodish style */
|
||||
body {
|
||||
@@ -113,7 +114,52 @@ div.toc p,a {
|
||||
|
||||
<!-- tocinfo
|
||||
{'highest level': 2,
|
||||
'sections': [('Format for electronic delivery of report and programs',
|
||||
'sections': [('Regression analysis and resampling methods',
|
||||
2,
|
||||
None,
|
||||
'regression-analysis-and-resampling-methods'),
|
||||
('Description of two-dimensional function',
|
||||
3,
|
||||
None,
|
||||
'description-of-two-dimensional-function'),
|
||||
('Part a): Paper and pencil part (also as weekly exercise for '
|
||||
'week 36)',
|
||||
3,
|
||||
None,
|
||||
'part-a-paper-and-pencil-part-also-as-weekly-exercise-for-week-36'),
|
||||
('Part b) : Ordinary Least Square (OLS) on the Franke function',
|
||||
3,
|
||||
None,
|
||||
'part-b-ordinary-least-square-ols-on-the-franke-function'),
|
||||
('Part c): Bias-variance trade-off and resampling techniques',
|
||||
3,
|
||||
None,
|
||||
'part-c-bias-variance-trade-off-and-resampling-techniques'),
|
||||
('Part d): Cross-validation as resampling techniques, adding '
|
||||
'more complexity',
|
||||
3,
|
||||
None,
|
||||
'part-d-cross-validation-as-resampling-techniques-adding-more-complexity'),
|
||||
('Part e): Ridge Regression on the Franke function with '
|
||||
'resampling',
|
||||
3,
|
||||
None,
|
||||
'part-e-ridge-regression-on-the-franke-function-with-resampling'),
|
||||
('Part f): Lasso Regression on the Franke function with '
|
||||
'resampling',
|
||||
3,
|
||||
None,
|
||||
'part-f-lasso-regression-on-the-franke-function-with-resampling'),
|
||||
('Part g): Analysis of real data',
|
||||
3,
|
||||
None,
|
||||
'part-g-analysis-of-real-data'),
|
||||
('Background literature', 2, None, 'background-literature'),
|
||||
('Introduction to numerical projects',
|
||||
2,
|
||||
None,
|
||||
'introduction-to-numerical-projects'),
|
||||
('Format for electronic delivery of report and programs',
|
||||
2,
|
||||
None,
|
||||
'format-for-electronic-delivery-of-report-and-programs'),
|
||||
@@ -124,7 +170,529 @@ div.toc p,a {
|
||||
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>Project 1 on Machine Learning, deadline October 7, 2022</h1>
|
||||
</center> <!-- document title -->
|
||||
|
||||
<!-- author(s): <a href="http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" target="_blank">Data Analysis and Machine Learning FYS-STK3155/FYS4155</a> -->
|
||||
<center>
|
||||
<b><a href="http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" target="_blank">Data Analysis and Machine Learning FYS-STK3155/FYS4155</a></b>
|
||||
</center>
|
||||
<!-- institution -->
|
||||
<center>
|
||||
<b>University of Oslo, Norway</b>
|
||||
</center>
|
||||
<br>
|
||||
<center>
|
||||
<h4>Sep 7, 2022</h4>
|
||||
</center> <!-- date -->
|
||||
<br>
|
||||
<h2 id="regression-analysis-and-resampling-methods">Regression analysis and resampling methods </h2>
|
||||
|
||||
<p>The main aim of this project is to study in more detail various
|
||||
regression methods, including the Ordinary Least Squares (OLS) method.
|
||||
In addition to the scientific part, in this course we want also to
|
||||
give you an experience in writing scientific reports. The format for
|
||||
the delivery of your answers is namely that of a scientific report. At
|
||||
for example
|
||||
<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md</tt></a>
|
||||
we detail how to write a report. Furthermore, at
|
||||
<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/</tt></a>
|
||||
you can find examples of previous reports. How to write reports will
|
||||
also be discussed during lectures and at the various lab sessions.
|
||||
</p>
|
||||
|
||||
<p><b>A small recommendation when developing the codes here</b>. Instead of
|
||||
jumping on to the two-dimensional function described below, we
|
||||
recommend to do the code development and testing with a simpler
|
||||
one-dimensional function, similar to those discussed in the exercises
|
||||
of week 35. A simple test, as discussed during the lectures the first
|
||||
two weeks is to set the design matrix equal to the identity
|
||||
matrix. Then your model should give a mean square error which is exactly equal to zero.
|
||||
When you are sure that your codes function well, you can then replace
|
||||
the one-dimensional test function with the two-dimensional <b>Franke</b> function
|
||||
discussed here.
|
||||
</p>
|
||||
|
||||
<p>The Franke function serves as a stepping stone towards the analysis of
|
||||
real topographic data. The latter is the last part of this project.
|
||||
</p>
|
||||
<h3 id="description-of-two-dimensional-function">Description of two-dimensional function </h3>
|
||||
|
||||
<p>We will first study how to fit polynomials to a specific
|
||||
two-dimensional function called <a href="http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf" target="_blank">Franke's
|
||||
function</a>. This
|
||||
is a function which has been widely used when testing various
|
||||
interpolation and fitting algorithms. Furthermore, after having
|
||||
established the model and the method, we will employ resamling
|
||||
techniques such as cross-validation and/or bootstrap in order to perform a
|
||||
proper assessment of our models. We will also study in detail the
|
||||
so-called Bias-Variance trade off.
|
||||
</p>
|
||||
|
||||
<p>The Franke function, which is a weighted sum of four exponentials reads as follows</p>
|
||||
$$
|
||||
\begin{align*}
|
||||
f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\
|
||||
&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }.
|
||||
\end{align*}
|
||||
$$
|
||||
|
||||
<p>The function will be defined for \( x,y\in [0,1] \). Our first step will
|
||||
be to perform an OLS regression analysis of this function, trying out
|
||||
a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y,
|
||||
x^2, y^2, xy, \dots] \). We will also include bootstrap first as a
|
||||
resampling technique. After that we will include the cross-validation
|
||||
technique. As discussed in the lectures for weeks 35 and 36,, we can
|
||||
use a uniform distribution to set up the arrays of values for \( x \) and
|
||||
\( y \), or as in the example below just a set of fixed values for \( x \) and
|
||||
\( y \) with a given step size. We will fit a function (for example a
|
||||
polynomial) of \( x \) and \( y \). Thereafter we will repeat much of the
|
||||
same procedure using the Ridge and Lasso regression methods,
|
||||
introducing thus a dependence on the bias (penalty) \( \lambda \).
|
||||
</p>
|
||||
|
||||
<p>Finally we are going to use (real) digital terrain data and try to
|
||||
reproduce these data using the same methods. We will also try to go
|
||||
beyond the second-order polynomials metioned above and explore
|
||||
which polynomial fits the data best.
|
||||
</p>
|
||||
|
||||
<p>The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)</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">from</span> <span style="color: #0000FF; font-weight: bold">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> Axes3D
|
||||
<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">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib.ticker</span> <span style="color: #008000; font-weight: bold">import</span> LinearLocator, FormatStrFormatter
|
||||
<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">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
|
||||
|
||||
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
|
||||
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Make data.</span>
|
||||
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0.05</span>)
|
||||
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0.05</span>)
|
||||
x, y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(x,y)
|
||||
|
||||
|
||||
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">FrankeFunction</span>(x,y):
|
||||
term1 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">0.25*</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>) <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>))
|
||||
term2 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>((<span style="color: #666666">9*</span>x<span style="color: #666666">+1</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">/49.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.1*</span>(<span style="color: #666666">9*</span>y<span style="color: #666666">+1</span>))
|
||||
term3 <span style="color: #666666">=</span> <span style="color: #666666">0.5*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-7</span>)<span style="color: #666666">**2/4.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-3</span>)<span style="color: #666666">**2</span>))
|
||||
term4 <span style="color: #666666">=</span> <span style="color: #666666">-0.2*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-4</span>)<span style="color: #666666">**2</span> <span style="color: #666666">-</span> (<span style="color: #666666">9*</span>y<span style="color: #666666">-7</span>)<span style="color: #666666">**2</span>)
|
||||
<span style="color: #008000; font-weight: bold">return</span> term1 <span style="color: #666666">+</span> term2 <span style="color: #666666">+</span> term3 <span style="color: #666666">+</span> term4
|
||||
|
||||
|
||||
z <span style="color: #666666">=</span> FrankeFunction(x, y)
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Plot the surface.</span>
|
||||
surf <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(x, y, z, cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>coolwarm,
|
||||
linewidth<span style="color: #666666">=0</span>, antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Customize the z axis.</span>
|
||||
ax<span style="color: #666666">.</span>set_zlim(<span style="color: #666666">-0.10</span>, <span style="color: #666666">1.40</span>)
|
||||
ax<span style="color: #666666">.</span>zaxis<span style="color: #666666">.</span>set_major_locator(LinearLocator(<span style="color: #666666">10</span>))
|
||||
ax<span style="color: #666666">.</span>zaxis<span style="color: #666666">.</span>set_major_formatter(FormatStrFormatter(<span style="color: #BA2121">'</span><span style="color: #BB6688; font-weight: bold">%.02f</span><span style="color: #BA2121">'</span>))
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Add a color bar which maps values to colors.</span>
|
||||
fig<span style="color: #666666">.</span>colorbar(surf, shrink<span style="color: #666666">=0.5</span>, aspect<span style="color: #666666">=5</span>)
|
||||
|
||||
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>
|
||||
<h3 id="part-a-paper-and-pencil-part-also-as-weekly-exercise-for-week-36">Part a): Paper and pencil part (also as weekly exercise for week 36) </h3>
|
||||
|
||||
<p>This exercise deals with various mean values and variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of <a href="https://www.springer.com/gp/book/9780387848570" target="_blank">Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer</a>).</p>
|
||||
|
||||
<p>The assumption we have made is
|
||||
that there exists a continuous function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim N(0, \sigma^2) \)
|
||||
which describes our data
|
||||
</p>
|
||||
$$
|
||||
\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
|
||||
$$
|
||||
|
||||
<p>We then approximate this function \( f(\boldsymbol{x}) \) with our model \( \boldsymbol{\tilde{y}} \) from the solution of the linear regression equations (ordinary least squares OLS), that is our
|
||||
function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we minimized \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), with
|
||||
</p>
|
||||
$$
|
||||
\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
|
||||
$$
|
||||
|
||||
<p>The matrix \( \boldsymbol{X} \) is the so-called design or feature matrix. </p>
|
||||
|
||||
<p>Show that the expectation value of \( \boldsymbol{y} \) for a given element \( i \) </p>
|
||||
$$
|
||||
\mathbb{E}(y_i) =\sum_{j}x_{ij} \beta_j=\mathbf{X}_{i, \ast} \, \boldsymbol{\beta},
|
||||
$$
|
||||
|
||||
<p>and that
|
||||
its variance is
|
||||
</p>
|
||||
$$
|
||||
\mbox{Var}(y_i) = \sigma^2.
|
||||
$$
|
||||
|
||||
<p>Hence, \( y_i \sim 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 \).
|
||||
</p>
|
||||
|
||||
<p>With the OLS expressions for the optimal parameters \( \boldsymbol{\hat{\beta}} \) show that</p>
|
||||
$$
|
||||
\mathbb{E}(\boldsymbol{\hat{\beta}}) = \boldsymbol{\beta}.
|
||||
$$
|
||||
|
||||
<p>Show finally that the variance of \( \boldsymbol{\beta} \) is</p>
|
||||
$$
|
||||
\mbox{Var}(\boldsymbol{\hat{\beta}}) = \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}.
|
||||
$$
|
||||
|
||||
<p>We can use the last expression when we define a so-called confidence interval for the parameters \( \beta \). .
|
||||
A given parameter \( \beta_j \) is given by the diagonal matrix element of the above matrix.
|
||||
</p>
|
||||
<h3 id="part-b-ordinary-least-square-ols-on-the-franke-function">Part b) : Ordinary Least Square (OLS) on the Franke function </h3>
|
||||
|
||||
<p>We will generate our own dataset for a function
|
||||
\( \mathrm{FrankeFunction}(x,y) \) with \( x,y \in [0,1] \). The function
|
||||
\( f(x,y) \) is the Franke function. You should explore also the addition
|
||||
of an added stochastic noise to this function using the normal
|
||||
distribution \( N(0,1) \).
|
||||
</p>
|
||||
|
||||
<p><em>Write your own code</em> (using either a matrix inversion or a singular
|
||||
value decomposition from e.g., <b>numpy</b> ) and perform a standard <b>ordinary least square regression</b>
|
||||
analysis using polynomials in \( x \) and \( y \) up to fifth order.
|
||||
</p>
|
||||
|
||||
<p>Evaluate the mean Squared error (MSE)</p>
|
||||
|
||||
$$ MSE(\boldsymbol{y},\tilde{\boldsymbol{y}}) = \frac{1}{n}
|
||||
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
|
||||
$$
|
||||
|
||||
<p>and the \( R^2 \) score function. If \( \tilde{\boldsymbol{y}}_i \) is the predicted
|
||||
value of the \( i-th \) sample and \( y_i \) is the corresponding true value,
|
||||
then the score \( R^2 \) is defined as
|
||||
</p>
|
||||
|
||||
$$
|
||||
R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
|
||||
$$
|
||||
|
||||
<p>where we have defined the mean value of \( \boldsymbol{y} \) as</p>
|
||||
|
||||
$$
|
||||
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
|
||||
$$
|
||||
|
||||
<p>Plot the resulting scores (MSE and R$^2$) as functions of the polynomial degree (here up to polymial degree five).
|
||||
Plot also the parameters \( \beta \) as you increase the order of the polynomial. Comment your results.
|
||||
</p>
|
||||
|
||||
<p>Your code has to include a scaling/centering of the data (for example by
|
||||
subtracting the mean value), and
|
||||
a split of the data in training and test data. For this exercise you can
|
||||
either write your own code or use for example the function for
|
||||
splitting training data provided by the library <b>Scikit-Learn</b> (make
|
||||
sure you have installed it). This function is called
|
||||
\( train\_test\_split \). <b>You should present a critical discussion of why and how you have scaled or not scaled the data</b>.
|
||||
</p>
|
||||
|
||||
<p>It is normal in essentially all Machine Learning studies to split the
|
||||
data in a training set and a test set (eventually also an additional
|
||||
validation set). There
|
||||
is no explicit recipe for how much data should be included as training
|
||||
data and say test data. An accepted rule of thumb is to use
|
||||
approximately \( 2/3 \) to \( 4/5 \) of the data as training data.
|
||||
</p>
|
||||
|
||||
<p>You can easily reuse the solutions to your exercises from week 35 and week 36.
|
||||
See also the lecture slides from week 35 and week 36.
|
||||
</p>
|
||||
<h3 id="part-c-bias-variance-trade-off-and-resampling-techniques">Part c): Bias-variance trade-off and resampling techniques </h3>
|
||||
|
||||
<p>Our aim here is to study the bias-variance trade-off by implementing the <b>bootstrap</b> resampling technique.</p>
|
||||
|
||||
<p>With a code which does OLS and includes resampling techniques,
|
||||
we will now discuss the bias-variance trade-off in the context of
|
||||
continuous predictions such as regression. However, many of the
|
||||
intuitions and ideas discussed here also carry over to classification
|
||||
tasks and basically all Machine Learning algorithms.
|
||||
</p>
|
||||
|
||||
<p>Before you perform an analysis of the bias-variance trade-off on your test data, make
|
||||
first a figure similar to Fig. 2.11 of Hastie, Tibshirani, and
|
||||
Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to
|
||||
indicate possible regions of low/high bias and variance. You will most likely not get an
|
||||
equally smooth curve!
|
||||
</p>
|
||||
|
||||
<p>With this result we move on to the bias-variance trade-off analysis.</p>
|
||||
|
||||
<p>Consider a
|
||||
dataset \( \mathcal{L} \) consisting of the data
|
||||
\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \).
|
||||
</p>
|
||||
|
||||
<p>As in part a), we assume that the true data is generated from a noisy model</p>
|
||||
|
||||
$$
|
||||
\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}.
|
||||
$$
|
||||
|
||||
<p>Here \( \epsilon \) is normally distributed with mean zero and standard
|
||||
deviation \( \sigma^2 \).
|
||||
</p>
|
||||
|
||||
<p>In our derivation of the ordinary least squares method we defined then
|
||||
an approximation to the function \( f \) in terms of the parameters
|
||||
\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model,
|
||||
that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \).
|
||||
</p>
|
||||
|
||||
<p>The parameters \( \boldsymbol{\beta} \) are in turn found by optimizing the means
|
||||
squared error via the so-called cost function
|
||||
</p>
|
||||
|
||||
$$
|
||||
C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
|
||||
$$
|
||||
|
||||
<p>Here the expected value \( \mathbb{E} \) is the sample value. </p>
|
||||
|
||||
<p>Show that you can rewrite this in terms of a term which contains the variance of the model itself (the so-called variance term), a
|
||||
term which measures the deviation from the true data and the mean value of the model (the bias term) and finally the variance of the noise.
|
||||
That is, show that
|
||||
</p>
|
||||
$$
|
||||
\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=(\mathrm{Bias}[\tilde{y}])^2+\mathrm{var}[\tilde{f}]+\sigma^2,
|
||||
$$
|
||||
|
||||
<p>with </p>
|
||||
$$
|
||||
(\mathrm{Bias}[\tilde{y}])^2=\left(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]\right)^2,
|
||||
$$
|
||||
|
||||
<p>and </p>
|
||||
$$
|
||||
\mathrm{var}[\tilde{f}]=\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2.
|
||||
$$
|
||||
|
||||
<p>The answer to this exercise should be included in the theory part of the report.
|
||||
Explain what the terms mean and discuss their interpretations.
|
||||
</p>
|
||||
|
||||
<p>Perform then a bias-variance analysis of the Franke function by
|
||||
studying the MSE value as function of the complexity of your model.
|
||||
</p>
|
||||
|
||||
<p>Discuss the bias and variance trade-off as function
|
||||
of your model complexity (the degree of the polynomial) and the number
|
||||
of data points, and possibly also your training and test data using the <b>bootstrap</b> resampling method.
|
||||
You can follow the code example in the jupyter-book at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff" target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff</tt></a>.
|
||||
</p>
|
||||
<h3 id="part-d-cross-validation-as-resampling-techniques-adding-more-complexity">Part d): Cross-validation as resampling techniques, adding more complexity </h3>
|
||||
|
||||
<p>The aim here is to write your own code for another widely popular
|
||||
resampling technique, the so-called cross-validation method. Again,
|
||||
before you start with cross-validation approach, you should scale your
|
||||
data if you think this is needed.
|
||||
</p>
|
||||
|
||||
<p>Implement the \( k \)-fold cross-validation algorithm (write your own
|
||||
code) and evaluate again the MSE function resulting
|
||||
from the test folds. You can compare your own code with that from
|
||||
<b>Scikit-Learn</b> if needed.
|
||||
</p>
|
||||
|
||||
<p>Compare the MSE you get from your cross-validation code with the one
|
||||
you got from your <b>bootstrap</b> code. Comment your results. Try \( 5-10 \)
|
||||
folds. You can also compare your own cross-validation code with the
|
||||
one provided by <b>Scikit-Learn</b>.
|
||||
</p>
|
||||
<h3 id="part-e-ridge-regression-on-the-franke-function-with-resampling">Part e): Ridge Regression on the Franke function with resampling </h3>
|
||||
|
||||
<p>Write your own code for the Ridge method, either using matrix
|
||||
inversion or the singular value decomposition as done in the previous
|
||||
exercise. Perform the same bootstrap analysis as in the
|
||||
part c) (for the same polynomials) and the cross-validation in part d) but now for different values of \( \lambda \). Compare and
|
||||
analyze your results with those obtained in parts b-d). Study the
|
||||
dependence on \( \lambda \).
|
||||
</p>
|
||||
|
||||
<p>Study also the bias-variance trade-off as function of various values of
|
||||
the parameter \( \lambda \). For the bias-variance trade-off, use the <b>bootstrap</b> resampling method. Comment your results.
|
||||
</p>
|
||||
<h3 id="part-f-lasso-regression-on-the-franke-function-with-resampling">Part f): Lasso Regression on the Franke function with resampling </h3>
|
||||
|
||||
<p>This exercise is essentially a repeat of the previous two ones, but now
|
||||
with Lasso regression. Write either your own code (difficult and optional) or, in this case,
|
||||
you can also use the functionalities of <b>Scikit-Learn</b> (recommended).
|
||||
Give a
|
||||
critical discussion of the three methods and a judgement of which
|
||||
model fits the data best. Perform here as well an analysis of the bias-variance trade-off using the <b>bootstrap</b> resampling technique and an analysis of the mean squared error using cross-validation.
|
||||
</p>
|
||||
<h3 id="part-g-analysis-of-real-data">Part g): Analysis of real data </h3>
|
||||
|
||||
<p>With our codes functioning and having been tested properly on a
|
||||
simpler function we are now ready to look at real data. We will
|
||||
essentially repeat in this exercise what was done in exercises 1-5. However, we
|
||||
need first to download the data and prepare properly the inputs to our
|
||||
codes. We are going to download digital terrain data from the website
|
||||
<a href="https://earthexplorer.usgs.gov/" target="_blank"><tt>https://earthexplorer.usgs.gov/</tt></a>,
|
||||
</p>
|
||||
|
||||
<p>Or, if you prefer, we have placed selected datafiles at <a href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles</tt></a></p>
|
||||
|
||||
<p>In order to obtain data for a specific region, you need to register as
|
||||
a user (free) at this website and then decide upon which area you want
|
||||
to fetch the digital terrain data from. In order to be able to read
|
||||
the data properly, you need to specify that the format should be <b>SRTM
|
||||
Arc-Second Global</b> and download the data as a <b>GeoTIF</b> file. The
|
||||
files are then stored in <em>tif</em> format which can be imported into a
|
||||
Python program using
|
||||
</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%;">scipy<span style="color: #666666">.</span>misc<span style="color: #666666">.</span>imread
|
||||
</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>Here is a simple part of a Python code which reads and plots the data
|
||||
from such files
|
||||
</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">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">from</span> <span style="color: #0000FF; font-weight: bold">imageio</span> <span style="color: #008000; font-weight: bold">import</span> imread
|
||||
<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">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> Axes3D
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
||||
|
||||
<span style="color: #408080; font-style: italic"># Load the terrain</span>
|
||||
terrain1 <span style="color: #666666">=</span> imread(<span style="color: #BA2121">'SRTM_data_Norway_1.tif'</span>)
|
||||
<span style="color: #408080; font-style: italic"># Show the terrain</span>
|
||||
plt<span style="color: #666666">.</span>figure()
|
||||
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">'Terrain over Norway 1'</span>)
|
||||
plt<span style="color: #666666">.</span>imshow(terrain1, cmap<span style="color: #666666">=</span><span style="color: #BA2121">'gray'</span>)
|
||||
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'X'</span>)
|
||||
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'Y'</span>)
|
||||
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>If you should have problems in downloading the digital terrain data,
|
||||
we provide two examples under the data folder of project 1. One is
|
||||
from a region close to Stavanger in Norway and the other Møsvatn
|
||||
Austfjell, again in Norway.
|
||||
Feel free to produce your own terrain data.
|
||||
</p>
|
||||
|
||||
<p>Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example <a href="https://www.kaggle.com/datasets" target="_blank">kaggle.com</a> for examples.</p>
|
||||
|
||||
<p>Our final part deals with the parameterization of your digital terrain
|
||||
data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial
|
||||
approximation and cross-validation as resampling technique to evaluate which
|
||||
model fits the data best.
|
||||
</p>
|
||||
|
||||
<p>At the end, you should present a critical evaluation of your results
|
||||
and discuss the applicability of these regression methods to the type
|
||||
of data presented here (either the terrain data we propose or other data sets).
|
||||
</p>
|
||||
<h2 id="background-literature">Background literature </h2>
|
||||
|
||||
<ol>
|
||||
<li> For a discussion and derivation of the variances and mean squared errors using linear regression, see the <a href="https://arxiv.org/abs/1509.09169" target="_blank">Lecture notes on ridge regression by Wessel N. van Wieringen</a></li>
|
||||
<li> The textbook of <a href="https://www.springer.com/gp/book/9780387848570" target="_blank">Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer</a>, chapters 3 and 7 are the most relevant ones for the analysis here.</li>
|
||||
</ol>
|
||||
<h2 id="introduction-to-numerical-projects">Introduction to numerical projects </h2>
|
||||
|
||||
<p>Here follows a brief recipe and recommendation on how to answer the various questions when preparing your answers. </p>
|
||||
|
||||
<ul>
|
||||
<li> Give a short description of the nature of the problem and the eventual numerical methods you have used.</li>
|
||||
<li> Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.</li>
|
||||
<li> Include the source code of your program. Comment your program properly. You should have the code at your GitHub/GitLab link. You can also place the code in an appendix of your report.</li>
|
||||
<li> If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.</li>
|
||||
<li> Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.</li>
|
||||
<li> Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.</li>
|
||||
<li> Try to give an interpretation of you results in your answers to the problems.</li>
|
||||
<li> Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.</li>
|
||||
<li> Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.</li>
|
||||
</ul>
|
||||
<h2 id="format-for-electronic-delivery-of-report-and-programs">Format for electronic delivery of report and programs </h2>
|
||||
|
||||
<p>The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008, Julia or Python. The following prescription should be followed when preparing the report:</p>
|
||||
|
||||
@@ -2,18 +2,825 @@
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "689b2940",
|
||||
"id": "7c5c1aa2",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
|
||||
"doconce format html Project1.do.txt -->"
|
||||
"doconce format html Project1.do.txt -->\n",
|
||||
"<!-- dom:TITLE: Project 1 on Machine Learning, deadline October 7, 2022 -->"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a3babcfe",
|
||||
"id": "8b966090",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"# Project 1 on Machine Learning, deadline October 7, 2022\n",
|
||||
"**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, University of Oslo, Norway\n",
|
||||
"\n",
|
||||
"Date: **Sep 7, 2022**"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "3c4d1c05",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"## Regression analysis and resampling methods\n",
|
||||
"\n",
|
||||
"The main aim of this project is to study in more detail various\n",
|
||||
"regression methods, including the Ordinary Least Squares (OLS) method.\n",
|
||||
"In addition to the scientific part, in this course we want also to\n",
|
||||
"give you an experience in writing scientific reports. The format for\n",
|
||||
"the delivery of your answers is namely that of a scientific report. At\n",
|
||||
"for example\n",
|
||||
"<https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md>\n",
|
||||
"we detail how to write a report. Furthermore, at\n",
|
||||
"<https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/>\n",
|
||||
"you can find examples of previous reports. How to write reports will\n",
|
||||
"also be discussed during lectures and at the various lab sessions.\n",
|
||||
"\n",
|
||||
"**A small recommendation when developing the codes here**. Instead of\n",
|
||||
"jumping on to the two-dimensional function described below, we\n",
|
||||
"recommend to do the code development and testing with a simpler\n",
|
||||
"one-dimensional function, similar to those discussed in the exercises\n",
|
||||
"of week 35. A simple test, as discussed during the lectures the first\n",
|
||||
"two weeks is to set the design matrix equal to the identity\n",
|
||||
"matrix. Then your model should give a mean square error which is exactly equal to zero.\n",
|
||||
"When you are sure that your codes function well, you can then replace\n",
|
||||
"the one-dimensional test function with the two-dimensional **Franke** function\n",
|
||||
"discussed here.\n",
|
||||
"\n",
|
||||
"The Franke function serves as a stepping stone towards the analysis of\n",
|
||||
"real topographic data. The latter is the last part of this project."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "d3c69b6e",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"### Description of two-dimensional function\n",
|
||||
"\n",
|
||||
"We will first study how to fit polynomials to a specific\n",
|
||||
"two-dimensional function called [Franke's\n",
|
||||
"function](http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf). This\n",
|
||||
"is a function which has been widely used when testing various\n",
|
||||
"interpolation and fitting algorithms. Furthermore, after having\n",
|
||||
"established the model and the method, we will employ resamling\n",
|
||||
"techniques such as cross-validation and/or bootstrap in order to perform a\n",
|
||||
"proper assessment of our models. We will also study in detail the\n",
|
||||
"so-called Bias-Variance trade off.\n",
|
||||
"\n",
|
||||
"The Franke function, which is a weighted sum of four exponentials reads as follows"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "bd45522d",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\begin{align*}\n",
|
||||
"f(x,y) &= \\frac{3}{4}\\exp{\\left(-\\frac{(9x-2)^2}{4} - \\frac{(9y-2)^2}{4}\\right)}+\\frac{3}{4}\\exp{\\left(-\\frac{(9x+1)^2}{49}- \\frac{(9y+1)}{10}\\right)} \\\\\n",
|
||||
"&+\\frac{1}{2}\\exp{\\left(-\\frac{(9x-7)^2}{4} - \\frac{(9y-3)^2}{4}\\right)} -\\frac{1}{5}\\exp{\\left(-(9x-4)^2 - (9y-7)^2\\right) }.\n",
|
||||
"\\end{align*}\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b2783b8a",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"The function will be defined for $x,y\\in [0,1]$. Our first step will\n",
|
||||
"be to perform an OLS regression analysis of this function, trying out\n",
|
||||
"a polynomial fit with an $x$ and $y$ dependence of the form $[x, y,\n",
|
||||
"x^2, y^2, xy, \\dots]$. We will also include bootstrap first as a\n",
|
||||
"resampling technique. After that we will include the cross-validation\n",
|
||||
"technique. As discussed in the lectures for weeks 35 and 36,, we can\n",
|
||||
"use a uniform distribution to set up the arrays of values for $x$ and\n",
|
||||
"$y$, or as in the example below just a set of fixed values for $x$ and\n",
|
||||
"$y$ with a given step size. We will fit a function (for example a\n",
|
||||
"polynomial) of $x$ and $y$. Thereafter we will repeat much of the\n",
|
||||
"same procedure using the Ridge and Lasso regression methods,\n",
|
||||
"introducing thus a dependence on the bias (penalty) $\\lambda$.\n",
|
||||
"\n",
|
||||
"Finally we are going to use (real) digital terrain data and try to\n",
|
||||
"reproduce these data using the same methods. We will also try to go\n",
|
||||
"beyond the second-order polynomials metioned above and explore \n",
|
||||
"which polynomial fits the data best.\n",
|
||||
"\n",
|
||||
"The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"id": "557c2d0f",
|
||||
"metadata": {
|
||||
"collapsed": false,
|
||||
"editable": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%matplotlib inline\n",
|
||||
"\n",
|
||||
"from mpl_toolkits.mplot3d import Axes3D\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"from matplotlib import cm\n",
|
||||
"from matplotlib.ticker import LinearLocator, FormatStrFormatter\n",
|
||||
"import numpy as np\n",
|
||||
"from random import random, seed\n",
|
||||
"\n",
|
||||
"fig = plt.figure()\n",
|
||||
"ax = fig.gca(projection='3d')\n",
|
||||
"\n",
|
||||
"# Make data.\n",
|
||||
"x = np.arange(0, 1, 0.05)\n",
|
||||
"y = np.arange(0, 1, 0.05)\n",
|
||||
"x, y = np.meshgrid(x,y)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def FrankeFunction(x,y):\n",
|
||||
" term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
|
||||
" term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
|
||||
" term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
|
||||
" term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
|
||||
" return term1 + term2 + term3 + term4\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"z = FrankeFunction(x, y)\n",
|
||||
"\n",
|
||||
"# Plot the surface.\n",
|
||||
"surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,\n",
|
||||
" linewidth=0, antialiased=False)\n",
|
||||
"\n",
|
||||
"# Customize the z axis.\n",
|
||||
"ax.set_zlim(-0.10, 1.40)\n",
|
||||
"ax.zaxis.set_major_locator(LinearLocator(10))\n",
|
||||
"ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n",
|
||||
"\n",
|
||||
"# Add a color bar which maps values to colors.\n",
|
||||
"fig.colorbar(surf, shrink=0.5, aspect=5)\n",
|
||||
"\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "ae7c13a2",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"### Part a): Paper and pencil part (also as weekly exercise for week 36)\n",
|
||||
"\n",
|
||||
"This exercise deals with various mean values and variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of [Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer](https://www.springer.com/gp/book/9780387848570)).\n",
|
||||
"\n",
|
||||
"The assumption we have made is \n",
|
||||
"that there exists a continuous function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim N(0, \\sigma^2)$\n",
|
||||
"which describes our data"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "4d436095",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "0e5b0d1f",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"We then approximate this function $f(\\boldsymbol{x})$ with our model $\\boldsymbol{\\tilde{y}}$ from the solution of the linear regression equations (ordinary least squares OLS), that is our\n",
|
||||
"function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we minimized $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, with"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "d6df0b06",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "81613471",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"The matrix $\\boldsymbol{X}$ is the so-called design or feature matrix. \n",
|
||||
"\n",
|
||||
"Show that the expectation value of $\\boldsymbol{y}$ for a given element $i$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7674e9a9",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mathbb{E}(y_i) =\\sum_{j}x_{ij} \\beta_j=\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta},\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "74c38893",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"and that\n",
|
||||
"its variance is"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "0ec96aab",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mbox{Var}(y_i) = \\sigma^2.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "915d48fa",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"Hence, $y_i \\sim N( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n",
|
||||
"mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$.\n",
|
||||
"\n",
|
||||
"With the OLS expressions for the optimal parameters $\\boldsymbol{\\hat{\\beta}}$ show that"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "5ddbefbc",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mathbb{E}(\\boldsymbol{\\hat{\\beta}}) = \\boldsymbol{\\beta}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "68625d58",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"Show finally that the variance of $\\boldsymbol{\\beta}$ is"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f99ce0d3",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mbox{Var}(\\boldsymbol{\\hat{\\beta}}) = \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "ad94b194",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"We can use the last expression when we define a so-called confidence interval for the parameters $\\beta$. .\n",
|
||||
"A given parameter $\\beta_j$ is given by the diagonal matrix element of the above matrix."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "aa87df59",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"### Part b) : Ordinary Least Square (OLS) on the Franke function\n",
|
||||
"\n",
|
||||
"We will generate our own dataset for a function\n",
|
||||
"$\\mathrm{FrankeFunction}(x,y)$ with $x,y \\in [0,1]$. The function\n",
|
||||
"$f(x,y)$ is the Franke function. You should explore also the addition\n",
|
||||
"of an added stochastic noise to this function using the normal\n",
|
||||
"distribution $N(0,1)$.\n",
|
||||
"\n",
|
||||
"*Write your own code* (using either a matrix inversion or a singular\n",
|
||||
"value decomposition from e.g., **numpy** ) and perform a standard **ordinary least square regression**\n",
|
||||
"analysis using polynomials in $x$ and $y$ up to fifth order.\n",
|
||||
"\n",
|
||||
"Evaluate the mean Squared error (MSE)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "2b4a2ae2",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"MSE(\\boldsymbol{y},\\tilde{\\boldsymbol{y}}) = \\frac{1}{n}\n",
|
||||
"\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b8fc68c4",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"and the $R^2$ score function. If $\\tilde{\\boldsymbol{y}}_i$ is the predicted\n",
|
||||
"value of the $i-th$ sample and $y_i$ is the corresponding true value,\n",
|
||||
"then the score $R^2$ is defined as"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "118e1ca7",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"R^2(\\boldsymbol{y}, \\tilde{\\boldsymbol{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1fb15d8c",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"where we have defined the mean value of $\\boldsymbol{y}$ as"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "cce55196",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "735026a7",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"Plot the resulting scores (MSE and R$^2$) as functions of the polynomial degree (here up to polymial degree five).\n",
|
||||
"Plot also the parameters $\\beta$ as you increase the order of the polynomial. Comment your results.\n",
|
||||
"\n",
|
||||
"Your code has to include a scaling/centering of the data (for example by\n",
|
||||
"subtracting the mean value), and\n",
|
||||
"a split of the data in training and test data. For this exercise you can\n",
|
||||
"either write your own code or use for example the function for\n",
|
||||
"splitting training data provided by the library **Scikit-Learn** (make\n",
|
||||
"sure you have installed it). This function is called\n",
|
||||
"$train\\_test\\_split$. **You should present a critical discussion of why and how you have scaled or not scaled the data**.\n",
|
||||
"\n",
|
||||
"It is normal in essentially all Machine Learning studies to split the\n",
|
||||
"data in a training set and a test set (eventually also an additional\n",
|
||||
"validation set). There\n",
|
||||
"is no explicit recipe for how much data should be included as training\n",
|
||||
"data and say test data. An accepted rule of thumb is to use\n",
|
||||
"approximately $2/3$ to $4/5$ of the data as training data.\n",
|
||||
"\n",
|
||||
"You can easily reuse the solutions to your exercises from week 35 and week 36.\n",
|
||||
"See also the lecture slides from week 35 and week 36."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "0ff52282",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"### Part c): Bias-variance trade-off and resampling techniques\n",
|
||||
"\n",
|
||||
"Our aim here is to study the bias-variance trade-off by implementing the **bootstrap** resampling technique.\n",
|
||||
"\n",
|
||||
"With a code which does OLS and includes resampling techniques, \n",
|
||||
"we will now discuss the bias-variance trade-off in the context of\n",
|
||||
"continuous predictions such as regression. However, many of the\n",
|
||||
"intuitions and ideas discussed here also carry over to classification\n",
|
||||
"tasks and basically all Machine Learning algorithms. \n",
|
||||
"\n",
|
||||
"Before you perform an analysis of the bias-variance trade-off on your test data, make\n",
|
||||
"first a figure similar to Fig. 2.11 of Hastie, Tibshirani, and\n",
|
||||
"Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to \n",
|
||||
"indicate possible regions of low/high bias and variance. You will most likely not get an\n",
|
||||
"equally smooth curve!\n",
|
||||
"\n",
|
||||
"With this result we move on to the bias-variance trade-off analysis.\n",
|
||||
"\n",
|
||||
"Consider a\n",
|
||||
"dataset $\\mathcal{L}$ consisting of the data\n",
|
||||
"$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$.\n",
|
||||
"\n",
|
||||
"As in part a), we assume that the true data is generated from a noisy model"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "fd1b3dc8",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "4e76a5b6",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"Here $\\epsilon$ is normally distributed with mean zero and standard\n",
|
||||
"deviation $\\sigma^2$.\n",
|
||||
"\n",
|
||||
"In our derivation of the ordinary least squares method we defined then\n",
|
||||
"an approximation to the function $f$ in terms of the parameters\n",
|
||||
"$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
|
||||
"that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$.\n",
|
||||
"\n",
|
||||
"The parameters $\\boldsymbol{\\beta}$ are in turn found by optimizing the means\n",
|
||||
"squared error via the so-called cost function"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "8f811765",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "64b77e21",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"Here the expected value $\\mathbb{E}$ is the sample value. \n",
|
||||
"\n",
|
||||
"Show that you can rewrite this in terms of a term which contains the variance of the model itself (the so-called variance term), a\n",
|
||||
"term which measures the deviation from the true data and the mean value of the model (the bias term) and finally the variance of the noise.\n",
|
||||
"That is, show that"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6714eb58",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=(\\mathrm{Bias}[\\tilde{y}])^2+\\mathrm{var}[\\tilde{f}]+\\sigma^2,\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6b83c5ed",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"with"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "dd7bbaf8",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"(\\mathrm{Bias}[\\tilde{y}])^2=\\left(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]\\right)^2,\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7f85569e",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"and"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b3551e16",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mathrm{var}[\\tilde{f}]=\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "087009c6",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"The answer to this exercise should be included in the theory part of the report.\n",
|
||||
"Explain what the terms mean and discuss their interpretations.\n",
|
||||
"\n",
|
||||
"Perform then a bias-variance analysis of the Franke function by\n",
|
||||
"studying the MSE value as function of the complexity of your model.\n",
|
||||
"\n",
|
||||
"Discuss the bias and variance trade-off as function\n",
|
||||
"of your model complexity (the degree of the polynomial) and the number\n",
|
||||
"of data points, and possibly also your training and test data using the **bootstrap** resampling method.\n",
|
||||
"You can follow the code example in the jupyter-book at <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff>."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b93880cc",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"### Part d): Cross-validation as resampling techniques, adding more complexity\n",
|
||||
"\n",
|
||||
"The aim here is to write your own code for another widely popular\n",
|
||||
"resampling technique, the so-called cross-validation method. Again,\n",
|
||||
"before you start with cross-validation approach, you should scale your\n",
|
||||
"data if you think this is needed.\n",
|
||||
"\n",
|
||||
"Implement the $k$-fold cross-validation algorithm (write your own\n",
|
||||
"code) and evaluate again the MSE function resulting\n",
|
||||
"from the test folds. You can compare your own code with that from\n",
|
||||
"**Scikit-Learn** if needed. \n",
|
||||
"\n",
|
||||
"Compare the MSE you get from your cross-validation code with the one\n",
|
||||
"you got from your **bootstrap** code. Comment your results. Try $5-10$\n",
|
||||
"folds. You can also compare your own cross-validation code with the\n",
|
||||
"one provided by **Scikit-Learn**."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "4dcca4a0",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"### Part e): Ridge Regression on the Franke function with resampling\n",
|
||||
"\n",
|
||||
"Write your own code for the Ridge method, either using matrix\n",
|
||||
"inversion or the singular value decomposition as done in the previous\n",
|
||||
"exercise. Perform the same bootstrap analysis as in the\n",
|
||||
"part c) (for the same polynomials) and the cross-validation in part d) but now for different values of $\\lambda$. Compare and\n",
|
||||
"analyze your results with those obtained in parts b-d). Study the\n",
|
||||
"dependence on $\\lambda$.\n",
|
||||
"\n",
|
||||
"Study also the bias-variance trade-off as function of various values of\n",
|
||||
"the parameter $\\lambda$. For the bias-variance trade-off, use the **bootstrap** resampling method. Comment your results."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "be345384",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"### Part f): Lasso Regression on the Franke function with resampling\n",
|
||||
"\n",
|
||||
"This exercise is essentially a repeat of the previous two ones, but now\n",
|
||||
"with Lasso regression. Write either your own code (difficult and optional) or, in this case,\n",
|
||||
"you can also use the functionalities of **Scikit-Learn** (recommended). \n",
|
||||
"Give a\n",
|
||||
"critical discussion of the three methods and a judgement of which\n",
|
||||
"model fits the data best. Perform here as well an analysis of the bias-variance trade-off using the **bootstrap** resampling technique and an analysis of the mean squared error using cross-validation."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "287209ae",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"### Part g): Analysis of real data\n",
|
||||
"\n",
|
||||
"With our codes functioning and having been tested properly on a\n",
|
||||
"simpler function we are now ready to look at real data. We will\n",
|
||||
"essentially repeat in this exercise what was done in exercises 1-5. However, we\n",
|
||||
"need first to download the data and prepare properly the inputs to our\n",
|
||||
"codes. We are going to download digital terrain data from the website\n",
|
||||
"<https://earthexplorer.usgs.gov/>,\n",
|
||||
"\n",
|
||||
"Or, if you prefer, we have placed selected datafiles at <https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles>\n",
|
||||
"\n",
|
||||
"In order to obtain data for a specific region, you need to register as\n",
|
||||
"a user (free) at this website and then decide upon which area you want\n",
|
||||
"to fetch the digital terrain data from. In order to be able to read\n",
|
||||
"the data properly, you need to specify that the format should be **SRTM\n",
|
||||
"Arc-Second Global** and download the data as a **GeoTIF** file. The\n",
|
||||
"files are then stored in *tif* format which can be imported into a\n",
|
||||
"Python program using"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"id": "a1ae6c6c",
|
||||
"metadata": {
|
||||
"collapsed": false,
|
||||
"editable": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"scipy.misc.imread"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "23a19e9e",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"Here is a simple part of a Python code which reads and plots the data\n",
|
||||
"from such files"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "6df62564",
|
||||
"metadata": {
|
||||
"collapsed": false,
|
||||
"editable": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"from imageio import imread\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"from mpl_toolkits.mplot3d import Axes3D\n",
|
||||
"from matplotlib import cm\n",
|
||||
"\n",
|
||||
"# Load the terrain\n",
|
||||
"terrain1 = imread('SRTM_data_Norway_1.tif')\n",
|
||||
"# Show the terrain\n",
|
||||
"plt.figure()\n",
|
||||
"plt.title('Terrain over Norway 1')\n",
|
||||
"plt.imshow(terrain1, cmap='gray')\n",
|
||||
"plt.xlabel('X')\n",
|
||||
"plt.ylabel('Y')\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "079f8895",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"If you should have problems in downloading the digital terrain data,\n",
|
||||
"we provide two examples under the data folder of project 1. One is\n",
|
||||
"from a region close to Stavanger in Norway and the other Møsvatn\n",
|
||||
"Austfjell, again in Norway.\n",
|
||||
"Feel free to produce your own terrain data.\n",
|
||||
"\n",
|
||||
"Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example [kaggle.com](https://www.kaggle.com/datasets) for examples.\n",
|
||||
"\n",
|
||||
"Our final part deals with the parameterization of your digital terrain\n",
|
||||
"data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial\n",
|
||||
"approximation and cross-validation as resampling technique to evaluate which\n",
|
||||
"model fits the data best.\n",
|
||||
"\n",
|
||||
"At the end, you should present a critical evaluation of your results\n",
|
||||
"and discuss the applicability of these regression methods to the type\n",
|
||||
"of data presented here (either the terrain data we propose or other data sets)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "931b5cd3",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"## Background literature\n",
|
||||
"\n",
|
||||
"1. For a discussion and derivation of the variances and mean squared errors using linear regression, see the [Lecture notes on ridge regression by Wessel N. van Wieringen](https://arxiv.org/abs/1509.09169)\n",
|
||||
"\n",
|
||||
"2. The textbook of [Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer](https://www.springer.com/gp/book/9780387848570), chapters 3 and 7 are the most relevant ones for the analysis here."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "c2f6b36e",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
"source": [
|
||||
"## Introduction to numerical projects\n",
|
||||
"\n",
|
||||
"Here follows a brief recipe and recommendation on how to answer the various questions when preparing your answers. \n",
|
||||
"\n",
|
||||
" * Give a short description of the nature of the problem and the eventual numerical methods you have used.\n",
|
||||
"\n",
|
||||
" * Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.\n",
|
||||
"\n",
|
||||
" * Include the source code of your program. Comment your program properly. You should have the code at your GitHub/GitLab link. You can also place the code in an appendix of your report.\n",
|
||||
"\n",
|
||||
" * If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.\n",
|
||||
"\n",
|
||||
" * Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.\n",
|
||||
"\n",
|
||||
" * Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.\n",
|
||||
"\n",
|
||||
" * Try to give an interpretation of you results in your answers to the problems.\n",
|
||||
"\n",
|
||||
" * Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.\n",
|
||||
"\n",
|
||||
" * Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "259801a7",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
@@ -35,7 +842,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "263b5ddb",
|
||||
"id": "57aac88f",
|
||||
"metadata": {
|
||||
"editable": true
|
||||
},
|
||||
|
||||
Binary file not shown.
@@ -45,6 +45,12 @@ final, % draft: marks overfull hboxes, figures with paths
|
||||
|
||||
\usepackage[pdftex]{graphicx}
|
||||
|
||||
\usepackage{ptex2tex}
|
||||
% #ifdef MINTED
|
||||
\usepackage{minted}
|
||||
\usemintedstyle{default}
|
||||
% #endif
|
||||
|
||||
\usepackage[T1]{fontenc}
|
||||
%\usepackage[latin1]{inputenc}
|
||||
\usepackage{ucs}
|
||||
@@ -97,6 +103,504 @@ final, % draft: marks overfull hboxes, figures with paths
|
||||
|
||||
% ------------------- main content ----------------------
|
||||
|
||||
|
||||
|
||||
% ----------------- title -------------------------
|
||||
|
||||
\thispagestyle{empty}
|
||||
|
||||
\begin{center}
|
||||
{\LARGE\bf
|
||||
\begin{spacing}{1.25}
|
||||
Project 1 on Machine Learning, deadline October 7, 2022
|
||||
\end{spacing}
|
||||
}
|
||||
\end{center}
|
||||
|
||||
% ----------------- author(s) -------------------------
|
||||
|
||||
\begin{center}
|
||||
{\bf \href{{http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html}}{Data Analysis and Machine Learning FYS-STK3155/FYS4155}}
|
||||
\end{center}
|
||||
|
||||
\begin{center}
|
||||
% List of all institutions:
|
||||
\centerline{{\small University of Oslo, Norway}}
|
||||
\end{center}
|
||||
|
||||
% ----------------- end author(s) -------------------------
|
||||
|
||||
% --- begin date ---
|
||||
\begin{center}
|
||||
Sep 7, 2022
|
||||
\end{center}
|
||||
% --- end date ---
|
||||
|
||||
\vspace{1cm}
|
||||
|
||||
|
||||
\subsection{Regression analysis and resampling methods}
|
||||
|
||||
The main aim of this project is to study in more detail various
|
||||
regression methods, including the Ordinary Least Squares (OLS) method.
|
||||
In addition to the scientific part, in this course we want also to
|
||||
give you an experience in writing scientific reports. The format for
|
||||
the delivery of your answers is namely that of a scientific report. At
|
||||
for example
|
||||
\href{{https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md}}{\nolinkurl{https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md}}
|
||||
we detail how to write a report. Furthermore, at
|
||||
\href{{https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/}}{\nolinkurl{https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/}}
|
||||
you can find examples of previous reports. How to write reports will
|
||||
also be discussed during lectures and at the various lab sessions.
|
||||
|
||||
\textbf{A small recommendation when developing the codes here}. Instead of
|
||||
jumping on to the two-dimensional function described below, we
|
||||
recommend to do the code development and testing with a simpler
|
||||
one-dimensional function, similar to those discussed in the exercises
|
||||
of week 35. A simple test, as discussed during the lectures the first
|
||||
two weeks is to set the design matrix equal to the identity
|
||||
matrix. Then your model should give a mean square error which is exactly equal to zero.
|
||||
When you are sure that your codes function well, you can then replace
|
||||
the one-dimensional test function with the two-dimensional \textbf{Franke} function
|
||||
discussed here.
|
||||
|
||||
The Franke function serves as a stepping stone towards the analysis of
|
||||
real topographic data. The latter is the last part of this project.
|
||||
|
||||
\paragraph{Description of two-dimensional function.}
|
||||
We will first study how to fit polynomials to a specific
|
||||
two-dimensional function called \href{{http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf}}{Franke's
|
||||
function}. This
|
||||
is a function which has been widely used when testing various
|
||||
interpolation and fitting algorithms. Furthermore, after having
|
||||
established the model and the method, we will employ resamling
|
||||
techniques such as cross-validation and/or bootstrap in order to perform a
|
||||
proper assessment of our models. We will also study in detail the
|
||||
so-called Bias-Variance trade off.
|
||||
|
||||
The Franke function, which is a weighted sum of four exponentials reads as follows
|
||||
\begin{align*}
|
||||
f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\
|
||||
&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }.
|
||||
\end{align*}
|
||||
|
||||
The function will be defined for $x,y\in [0,1]$. Our first step will
|
||||
be to perform an OLS regression analysis of this function, trying out
|
||||
a polynomial fit with an $x$ and $y$ dependence of the form $[x, y,
|
||||
x^2, y^2, xy, \dots]$. We will also include bootstrap first as a
|
||||
resampling technique. After that we will include the cross-validation
|
||||
technique. As discussed in the lectures for weeks 35 and 36,, we can
|
||||
use a uniform distribution to set up the arrays of values for $x$ and
|
||||
$y$, or as in the example below just a set of fixed values for $x$ and
|
||||
$y$ with a given step size. We will fit a function (for example a
|
||||
polynomial) of $x$ and $y$. Thereafter we will repeat much of the
|
||||
same procedure using the Ridge and Lasso regression methods,
|
||||
introducing thus a dependence on the bias (penalty) $\lambda$.
|
||||
|
||||
Finally we are going to use (real) digital terrain data and try to
|
||||
reproduce these data using the same methods. We will also try to go
|
||||
beyond the second-order polynomials metioned above and explore
|
||||
which polynomial fits the data best.
|
||||
|
||||
The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
\bpycod
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib import cm
|
||||
from matplotlib.ticker import LinearLocator, FormatStrFormatter
|
||||
import numpy as np
|
||||
from random import random, seed
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.gca(projection='3d')
|
||||
|
||||
# Make data.
|
||||
x = np.arange(0, 1, 0.05)
|
||||
y = np.arange(0, 1, 0.05)
|
||||
x, y = np.meshgrid(x,y)
|
||||
|
||||
|
||||
def FrankeFunction(x,y):
|
||||
term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
|
||||
term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
|
||||
term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
|
||||
term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
|
||||
return term1 + term2 + term3 + term4
|
||||
|
||||
|
||||
z = FrankeFunction(x, y)
|
||||
|
||||
# Plot the surface.
|
||||
surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
|
||||
linewidth=0, antialiased=False)
|
||||
|
||||
# Customize the z axis.
|
||||
ax.set_zlim(-0.10, 1.40)
|
||||
ax.zaxis.set_major_locator(LinearLocator(10))
|
||||
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
|
||||
|
||||
# Add a color bar which maps values to colors.
|
||||
fig.colorbar(surf, shrink=0.5, aspect=5)
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
\epycod
|
||||
|
||||
|
||||
\paragraph{Part a): Paper and pencil part (also as weekly exercise for week 36).}
|
||||
This exercise deals with various mean values and variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}).
|
||||
|
||||
The assumption we have made is
|
||||
that there exists a continuous function $f(\bm{x})$ and a normal distributed error $\bm{\varepsilon}\sim N(0, \sigma^2)$
|
||||
which describes our data
|
||||
\[
|
||||
\bm{y} = f(\bm{x})+\bm{\varepsilon}
|
||||
\]
|
||||
|
||||
We then approximate this function $f(\bm{x})$ with our model $\bm{\tilde{y}}$ from the solution of the linear regression equations (ordinary least squares OLS), that is our
|
||||
function $f$ is approximated by $\bm{\tilde{y}}$ where we minimized $(\bm{y}-\bm{\tilde{y}})^2$, with
|
||||
\[
|
||||
\bm{\tilde{y}} = \bm{X}\bm{\beta}.
|
||||
\]
|
||||
The matrix $\bm{X}$ is the so-called design or feature matrix.
|
||||
|
||||
Show that the expectation value of $\bm{y}$ for a given element $i$
|
||||
\[
|
||||
\mathbb{E}(y_i) =\sum_{j}x_{ij} \beta_j=\mathbf{X}_{i, \ast} \, \bm{\beta},
|
||||
\]
|
||||
and that
|
||||
its variance is
|
||||
\[
|
||||
\mbox{Var}(y_i) = \sigma^2.
|
||||
\]
|
||||
Hence, $y_i \sim N( \mathbf{X}_{i, \ast} \, \bm{\beta}, \sigma^2)$, that is $\bm{y}$ follows a normal distribution with
|
||||
mean value $\bm{X}\bm{\beta}$ and variance $\sigma^2$.
|
||||
|
||||
With the OLS expressions for the optimal parameters $\bm{\hat{\beta}}$ show that
|
||||
\[
|
||||
\mathbb{E}(\bm{\hat{\beta}}) = \bm{\beta}.
|
||||
\]
|
||||
Show finally that the variance of $\bm{\beta}$ is
|
||||
\[
|
||||
\mbox{Var}(\bm{\hat{\beta}}) = \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}.
|
||||
\]
|
||||
|
||||
We can use the last expression when we define a so-called confidence interval for the parameters $\beta$. .
|
||||
A given parameter $\beta_j$ is given by the diagonal matrix element of the above matrix.
|
||||
|
||||
\paragraph{Part b) : Ordinary Least Square (OLS) on the Franke function.}
|
||||
We will generate our own dataset for a function
|
||||
$\mathrm{FrankeFunction}(x,y)$ with $x,y \in [0,1]$. The function
|
||||
$f(x,y)$ is the Franke function. You should explore also the addition
|
||||
of an added stochastic noise to this function using the normal
|
||||
distribution $N(0,1)$.
|
||||
|
||||
\emph{Write your own code} (using either a matrix inversion or a singular
|
||||
value decomposition from e.g., \textbf{numpy} ) and perform a standard \textbf{ordinary least square regression}
|
||||
analysis using polynomials in $x$ and $y$ up to fifth order.
|
||||
|
||||
Evaluate the mean Squared error (MSE)
|
||||
|
||||
\[ MSE(\bm{y},\tilde{\bm{y}}) = \frac{1}{n}
|
||||
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
|
||||
\]
|
||||
|
||||
and the $R^2$ score function. If $\tilde{\bm{y}}_i$ is the predicted
|
||||
value of the $i-th$ sample and $y_i$ is the corresponding true value,
|
||||
then the score $R^2$ is defined as
|
||||
|
||||
\[
|
||||
R^2(\bm{y}, \tilde{\bm{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
|
||||
\]
|
||||
|
||||
where we have defined the mean value of $\bm{y}$ as
|
||||
|
||||
\[
|
||||
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
|
||||
\]
|
||||
|
||||
Plot the resulting scores (MSE and R$^2$) as functions of the polynomial degree (here up to polymial degree five).
|
||||
Plot also the parameters $\beta$ as you increase the order of the polynomial. Comment your results.
|
||||
|
||||
Your code has to include a scaling/centering of the data (for example by
|
||||
subtracting the mean value), and
|
||||
a split of the data in training and test data. For this exercise you can
|
||||
either write your own code or use for example the function for
|
||||
splitting training data provided by the library \textbf{Scikit-Learn} (make
|
||||
sure you have installed it). This function is called
|
||||
$train\_test\_split$. \textbf{You should present a critical discussion of why and how you have scaled or not scaled the data}.
|
||||
|
||||
It is normal in essentially all Machine Learning studies to split the
|
||||
data in a training set and a test set (eventually also an additional
|
||||
validation set). There
|
||||
is no explicit recipe for how much data should be included as training
|
||||
data and say test data. An accepted rule of thumb is to use
|
||||
approximately $2/3$ to $4/5$ of the data as training data.
|
||||
|
||||
You can easily reuse the solutions to your exercises from week 35 and week 36.
|
||||
See also the lecture slides from week 35 and week 36.
|
||||
|
||||
\paragraph{Part c): Bias-variance trade-off and resampling techniques.}
|
||||
Our aim here is to study the bias-variance trade-off by implementing the \textbf{bootstrap} resampling technique.
|
||||
|
||||
With a code which does OLS and includes resampling techniques,
|
||||
we will now discuss the bias-variance trade-off in the context of
|
||||
continuous predictions such as regression. However, many of the
|
||||
intuitions and ideas discussed here also carry over to classification
|
||||
tasks and basically all Machine Learning algorithms.
|
||||
|
||||
Before you perform an analysis of the bias-variance trade-off on your test data, make
|
||||
first a figure similar to Fig.~2.11 of Hastie, Tibshirani, and
|
||||
Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to
|
||||
indicate possible regions of low/high bias and variance. You will most likely not get an
|
||||
equally smooth curve!
|
||||
|
||||
With this result we move on to the bias-variance trade-off analysis.
|
||||
|
||||
Consider a
|
||||
dataset $\mathcal{L}$ consisting of the data
|
||||
$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$.
|
||||
|
||||
As in part a), we assume that the true data is generated from a noisy model
|
||||
|
||||
\[
|
||||
\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon}.
|
||||
\]
|
||||
|
||||
Here $\epsilon$ is normally distributed with mean zero and standard
|
||||
deviation $\sigma^2$.
|
||||
|
||||
In our derivation of the ordinary least squares method we defined then
|
||||
an approximation to the function $f$ in terms of the parameters
|
||||
$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model,
|
||||
that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$.
|
||||
|
||||
The parameters $\bm{\beta}$ are in turn found by optimizing the means
|
||||
squared error via the so-called cost function
|
||||
|
||||
\[
|
||||
C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right].
|
||||
\]
|
||||
Here the expected value $\mathbb{E}$ is the sample value.
|
||||
|
||||
Show that you can rewrite this in terms of a term which contains the variance of the model itself (the so-called variance term), a
|
||||
term which measures the deviation from the true data and the mean value of the model (the bias term) and finally the variance of the noise.
|
||||
That is, show that
|
||||
\[
|
||||
\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=(\mathrm{Bias}[\tilde{y}])^2+\mathrm{var}[\tilde{f}]+\sigma^2,
|
||||
\]
|
||||
with
|
||||
\[
|
||||
(\mathrm{Bias}[\tilde{y}])^2=\left(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right]\right)^2,
|
||||
\]
|
||||
and
|
||||
\[
|
||||
\mathrm{var}[\tilde{f}]=\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2.
|
||||
\]
|
||||
The answer to this exercise should be included in the theory part of the report.
|
||||
Explain what the terms mean and discuss their interpretations.
|
||||
|
||||
Perform then a bias-variance analysis of the Franke function by
|
||||
studying the MSE value as function of the complexity of your model.
|
||||
|
||||
Discuss the bias and variance trade-off as function
|
||||
of your model complexity (the degree of the polynomial) and the number
|
||||
of data points, and possibly also your training and test data using the \textbf{bootstrap} resampling method.
|
||||
You can follow the code example in the jupyter-book at \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html\#the-bias-variance-tradeoff}}.
|
||||
|
||||
\paragraph{Part d): Cross-validation as resampling techniques, adding more complexity.}
|
||||
The aim here is to write your own code for another widely popular
|
||||
resampling technique, the so-called cross-validation method. Again,
|
||||
before you start with cross-validation approach, you should scale your
|
||||
data if you think this is needed.
|
||||
|
||||
Implement the $k$-fold cross-validation algorithm (write your own
|
||||
code) and evaluate again the MSE function resulting
|
||||
from the test folds. You can compare your own code with that from
|
||||
\textbf{Scikit-Learn} if needed.
|
||||
|
||||
Compare the MSE you get from your cross-validation code with the one
|
||||
you got from your \textbf{bootstrap} code. Comment your results. Try $5-10$
|
||||
folds. You can also compare your own cross-validation code with the
|
||||
one provided by \textbf{Scikit-Learn}.
|
||||
|
||||
\paragraph{Part e): Ridge Regression on the Franke function with resampling.}
|
||||
Write your own code for the Ridge method, either using matrix
|
||||
inversion or the singular value decomposition as done in the previous
|
||||
exercise. Perform the same bootstrap analysis as in the
|
||||
part c) (for the same polynomials) and the cross-validation in part d) but now for different values of $\lambda$. Compare and
|
||||
analyze your results with those obtained in parts b-d). Study the
|
||||
dependence on $\lambda$.
|
||||
|
||||
Study also the bias-variance trade-off as function of various values of
|
||||
the parameter $\lambda$. For the bias-variance trade-off, use the \textbf{bootstrap} resampling method. Comment your results.
|
||||
|
||||
\paragraph{Part f): Lasso Regression on the Franke function with resampling.}
|
||||
This exercise is essentially a repeat of the previous two ones, but now
|
||||
with Lasso regression. Write either your own code (difficult and optional) or, in this case,
|
||||
you can also use the functionalities of \textbf{Scikit-Learn} (recommended).
|
||||
Give a
|
||||
critical discussion of the three methods and a judgement of which
|
||||
model fits the data best. Perform here as well an analysis of the bias-variance trade-off using the \textbf{bootstrap} resampling technique and an analysis of the mean squared error using cross-validation.
|
||||
|
||||
\paragraph{Part g): Analysis of real data.}
|
||||
With our codes functioning and having been tested properly on a
|
||||
simpler function we are now ready to look at real data. We will
|
||||
essentially repeat in this exercise what was done in exercises 1-5. However, we
|
||||
need first to download the data and prepare properly the inputs to our
|
||||
codes. We are going to download digital terrain data from the website
|
||||
\href{{https://earthexplorer.usgs.gov/}}{\nolinkurl{https://earthexplorer.usgs.gov/}},
|
||||
|
||||
Or, if you prefer, we have placed selected datafiles at \href{{https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles}}{\nolinkurl{https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles}}
|
||||
|
||||
In order to obtain data for a specific region, you need to register as
|
||||
a user (free) at this website and then decide upon which area you want
|
||||
to fetch the digital terrain data from. In order to be able to read
|
||||
the data properly, you need to specify that the format should be \textbf{SRTM
|
||||
Arc-Second Global} and download the data as a \textbf{GeoTIF} file. The
|
||||
files are then stored in \emph{tif} format which can be imported into a
|
||||
Python program using
|
||||
|
||||
|
||||
|
||||
\bpycod
|
||||
scipy.misc.imread
|
||||
|
||||
\epycod
|
||||
|
||||
|
||||
Here is a simple part of a Python code which reads and plots the data
|
||||
from such files
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
\bpycod
|
||||
import numpy as np
|
||||
from imageio import imread
|
||||
import matplotlib.pyplot as plt
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
from matplotlib import cm
|
||||
|
||||
# Load the terrain
|
||||
terrain1 = imread('SRTM_data_Norway_1.tif')
|
||||
# Show the terrain
|
||||
plt.figure()
|
||||
plt.title('Terrain over Norway 1')
|
||||
plt.imshow(terrain1, cmap='gray')
|
||||
plt.xlabel('X')
|
||||
plt.ylabel('Y')
|
||||
plt.show()
|
||||
|
||||
\epycod
|
||||
|
||||
|
||||
If you should have problems in downloading the digital terrain data,
|
||||
we provide two examples under the data folder of project 1. One is
|
||||
from a region close to Stavanger in Norway and the other Møsvatn
|
||||
Austfjell, again in Norway.
|
||||
Feel free to produce your own terrain data.
|
||||
|
||||
Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example \href{{https://www.kaggle.com/datasets}}{kaggle.com} for examples.
|
||||
|
||||
Our final part deals with the parameterization of your digital terrain
|
||||
data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial
|
||||
approximation and cross-validation as resampling technique to evaluate which
|
||||
model fits the data best.
|
||||
|
||||
At the end, you should present a critical evaluation of your results
|
||||
and discuss the applicability of these regression methods to the type
|
||||
of data presented here (either the terrain data we propose or other data sets).
|
||||
|
||||
\subsection{Background literature}
|
||||
|
||||
\begin{enumerate}
|
||||
\item For a discussion and derivation of the variances and mean squared errors using linear regression, see the \href{{https://arxiv.org/abs/1509.09169}}{Lecture notes on ridge regression by Wessel N. van Wieringen}
|
||||
|
||||
\item The textbook of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}, chapters 3 and 7 are the most relevant ones for the analysis here.
|
||||
\end{enumerate}
|
||||
|
||||
\noindent
|
||||
\subsection{Introduction to numerical projects}
|
||||
|
||||
Here follows a brief recipe and recommendation on how to answer the various questions when preparing your answers.
|
||||
|
||||
\begin{itemize}
|
||||
\item Give a short description of the nature of the problem and the eventual numerical methods you have used.
|
||||
|
||||
\item Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.
|
||||
|
||||
\item Include the source code of your program. Comment your program properly. You should have the code at your GitHub/GitLab link. You can also place the code in an appendix of your report.
|
||||
|
||||
\item If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.
|
||||
|
||||
\item Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.
|
||||
|
||||
\item Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.
|
||||
|
||||
\item Try to give an interpretation of you results in your answers to the problems.
|
||||
|
||||
\item Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.
|
||||
|
||||
\item Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.
|
||||
\end{itemize}
|
||||
|
||||
\noindent
|
||||
\subsection{Format for electronic delivery of report and programs}
|
||||
|
||||
The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008, Julia or Python. The following prescription should be followed when preparing the report:
|
||||
|
||||
Binary file not shown.
@@ -20,6 +20,8 @@ final, % draft: marks overfull hboxes, figures with paths
|
||||
|
||||
\usepackage[pdftex]{graphicx}
|
||||
|
||||
\usepackage{fancyvrb} % packages needed for verbatim environments
|
||||
|
||||
\usepackage[T1]{fontenc}
|
||||
%\usepackage[latin1]{inputenc}
|
||||
\usepackage{ucs}
|
||||
@@ -71,6 +73,504 @@ final, % draft: marks overfull hboxes, figures with paths
|
||||
|
||||
% ------------------- main content ----------------------
|
||||
|
||||
|
||||
|
||||
% ----------------- title -------------------------
|
||||
|
||||
\thispagestyle{empty}
|
||||
|
||||
\begin{center}
|
||||
{\LARGE\bf
|
||||
\begin{spacing}{1.25}
|
||||
Project 1 on Machine Learning, deadline October 7, 2022
|
||||
\end{spacing}
|
||||
}
|
||||
\end{center}
|
||||
|
||||
% ----------------- author(s) -------------------------
|
||||
|
||||
\begin{center}
|
||||
{\bf \href{{http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html}}{Data Analysis and Machine Learning FYS-STK3155/FYS4155}}
|
||||
\end{center}
|
||||
|
||||
\begin{center}
|
||||
% List of all institutions:
|
||||
\centerline{{\small University of Oslo, Norway}}
|
||||
\end{center}
|
||||
|
||||
% ----------------- end author(s) -------------------------
|
||||
|
||||
% --- begin date ---
|
||||
\begin{center}
|
||||
Sep 7, 2022
|
||||
\end{center}
|
||||
% --- end date ---
|
||||
|
||||
\vspace{1cm}
|
||||
|
||||
|
||||
\subsection*{Regression analysis and resampling methods}
|
||||
|
||||
The main aim of this project is to study in more detail various
|
||||
regression methods, including the Ordinary Least Squares (OLS) method.
|
||||
In addition to the scientific part, in this course we want also to
|
||||
give you an experience in writing scientific reports. The format for
|
||||
the delivery of your answers is namely that of a scientific report. At
|
||||
for example
|
||||
\href{{https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md}}{\nolinkurl{https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md}}
|
||||
we detail how to write a report. Furthermore, at
|
||||
\href{{https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/}}{\nolinkurl{https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/}}
|
||||
you can find examples of previous reports. How to write reports will
|
||||
also be discussed during lectures and at the various lab sessions.
|
||||
|
||||
\textbf{A small recommendation when developing the codes here}. Instead of
|
||||
jumping on to the two-dimensional function described below, we
|
||||
recommend to do the code development and testing with a simpler
|
||||
one-dimensional function, similar to those discussed in the exercises
|
||||
of week 35. A simple test, as discussed during the lectures the first
|
||||
two weeks is to set the design matrix equal to the identity
|
||||
matrix. Then your model should give a mean square error which is exactly equal to zero.
|
||||
When you are sure that your codes function well, you can then replace
|
||||
the one-dimensional test function with the two-dimensional \textbf{Franke} function
|
||||
discussed here.
|
||||
|
||||
The Franke function serves as a stepping stone towards the analysis of
|
||||
real topographic data. The latter is the last part of this project.
|
||||
|
||||
\paragraph{Description of two-dimensional function.}
|
||||
We will first study how to fit polynomials to a specific
|
||||
two-dimensional function called \href{{http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf}}{Franke's
|
||||
function}. This
|
||||
is a function which has been widely used when testing various
|
||||
interpolation and fitting algorithms. Furthermore, after having
|
||||
established the model and the method, we will employ resamling
|
||||
techniques such as cross-validation and/or bootstrap in order to perform a
|
||||
proper assessment of our models. We will also study in detail the
|
||||
so-called Bias-Variance trade off.
|
||||
|
||||
The Franke function, which is a weighted sum of four exponentials reads as follows
|
||||
\begin{align*}
|
||||
f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\
|
||||
&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }.
|
||||
\end{align*}
|
||||
|
||||
The function will be defined for $x,y\in [0,1]$. Our first step will
|
||||
be to perform an OLS regression analysis of this function, trying out
|
||||
a polynomial fit with an $x$ and $y$ dependence of the form $[x, y,
|
||||
x^2, y^2, xy, \dots]$. We will also include bootstrap first as a
|
||||
resampling technique. After that we will include the cross-validation
|
||||
technique. As discussed in the lectures for weeks 35 and 36,, we can
|
||||
use a uniform distribution to set up the arrays of values for $x$ and
|
||||
$y$, or as in the example below just a set of fixed values for $x$ and
|
||||
$y$ with a given step size. We will fit a function (for example a
|
||||
polynomial) of $x$ and $y$. Thereafter we will repeat much of the
|
||||
same procedure using the Ridge and Lasso regression methods,
|
||||
introducing thus a dependence on the bias (penalty) $\lambda$.
|
||||
|
||||
Finally we are going to use (real) digital terrain data and try to
|
||||
reproduce these data using the same methods. We will also try to go
|
||||
beyond the second-order polynomials metioned above and explore
|
||||
which polynomial fits the data best.
|
||||
|
||||
The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
\begin{verbatim}
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib import cm
|
||||
from matplotlib.ticker import LinearLocator, FormatStrFormatter
|
||||
import numpy as np
|
||||
from random import random, seed
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.gca(projection='3d')
|
||||
|
||||
# Make data.
|
||||
x = np.arange(0, 1, 0.05)
|
||||
y = np.arange(0, 1, 0.05)
|
||||
x, y = np.meshgrid(x,y)
|
||||
|
||||
|
||||
def FrankeFunction(x,y):
|
||||
term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
|
||||
term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
|
||||
term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
|
||||
term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
|
||||
return term1 + term2 + term3 + term4
|
||||
|
||||
|
||||
z = FrankeFunction(x, y)
|
||||
|
||||
# Plot the surface.
|
||||
surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
|
||||
linewidth=0, antialiased=False)
|
||||
|
||||
# Customize the z axis.
|
||||
ax.set_zlim(-0.10, 1.40)
|
||||
ax.zaxis.set_major_locator(LinearLocator(10))
|
||||
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
|
||||
|
||||
# Add a color bar which maps values to colors.
|
||||
fig.colorbar(surf, shrink=0.5, aspect=5)
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
\end{verbatim}
|
||||
|
||||
|
||||
\paragraph{Part a): Paper and pencil part (also as weekly exercise for week 36).}
|
||||
This exercise deals with various mean values and variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}).
|
||||
|
||||
The assumption we have made is
|
||||
that there exists a continuous function $f(\bm{x})$ and a normal distributed error $\bm{\varepsilon}\sim N(0, \sigma^2)$
|
||||
which describes our data
|
||||
\[
|
||||
\bm{y} = f(\bm{x})+\bm{\varepsilon}
|
||||
\]
|
||||
|
||||
We then approximate this function $f(\bm{x})$ with our model $\bm{\tilde{y}}$ from the solution of the linear regression equations (ordinary least squares OLS), that is our
|
||||
function $f$ is approximated by $\bm{\tilde{y}}$ where we minimized $(\bm{y}-\bm{\tilde{y}})^2$, with
|
||||
\[
|
||||
\bm{\tilde{y}} = \bm{X}\bm{\beta}.
|
||||
\]
|
||||
The matrix $\bm{X}$ is the so-called design or feature matrix.
|
||||
|
||||
Show that the expectation value of $\bm{y}$ for a given element $i$
|
||||
\[
|
||||
\mathbb{E}(y_i) =\sum_{j}x_{ij} \beta_j=\mathbf{X}_{i, \ast} \, \bm{\beta},
|
||||
\]
|
||||
and that
|
||||
its variance is
|
||||
\[
|
||||
\mbox{Var}(y_i) = \sigma^2.
|
||||
\]
|
||||
Hence, $y_i \sim N( \mathbf{X}_{i, \ast} \, \bm{\beta}, \sigma^2)$, that is $\bm{y}$ follows a normal distribution with
|
||||
mean value $\bm{X}\bm{\beta}$ and variance $\sigma^2$.
|
||||
|
||||
With the OLS expressions for the optimal parameters $\bm{\hat{\beta}}$ show that
|
||||
\[
|
||||
\mathbb{E}(\bm{\hat{\beta}}) = \bm{\beta}.
|
||||
\]
|
||||
Show finally that the variance of $\bm{\beta}$ is
|
||||
\[
|
||||
\mbox{Var}(\bm{\hat{\beta}}) = \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}.
|
||||
\]
|
||||
|
||||
We can use the last expression when we define a so-called confidence interval for the parameters $\beta$. .
|
||||
A given parameter $\beta_j$ is given by the diagonal matrix element of the above matrix.
|
||||
|
||||
\paragraph{Part b) : Ordinary Least Square (OLS) on the Franke function.}
|
||||
We will generate our own dataset for a function
|
||||
$\mathrm{FrankeFunction}(x,y)$ with $x,y \in [0,1]$. The function
|
||||
$f(x,y)$ is the Franke function. You should explore also the addition
|
||||
of an added stochastic noise to this function using the normal
|
||||
distribution $N(0,1)$.
|
||||
|
||||
\emph{Write your own code} (using either a matrix inversion or a singular
|
||||
value decomposition from e.g., \textbf{numpy} ) and perform a standard \textbf{ordinary least square regression}
|
||||
analysis using polynomials in $x$ and $y$ up to fifth order.
|
||||
|
||||
Evaluate the mean Squared error (MSE)
|
||||
|
||||
\[ MSE(\bm{y},\tilde{\bm{y}}) = \frac{1}{n}
|
||||
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
|
||||
\]
|
||||
|
||||
and the $R^2$ score function. If $\tilde{\bm{y}}_i$ is the predicted
|
||||
value of the $i-th$ sample and $y_i$ is the corresponding true value,
|
||||
then the score $R^2$ is defined as
|
||||
|
||||
\[
|
||||
R^2(\bm{y}, \tilde{\bm{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
|
||||
\]
|
||||
|
||||
where we have defined the mean value of $\bm{y}$ as
|
||||
|
||||
\[
|
||||
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
|
||||
\]
|
||||
|
||||
Plot the resulting scores (MSE and R$^2$) as functions of the polynomial degree (here up to polymial degree five).
|
||||
Plot also the parameters $\beta$ as you increase the order of the polynomial. Comment your results.
|
||||
|
||||
Your code has to include a scaling/centering of the data (for example by
|
||||
subtracting the mean value), and
|
||||
a split of the data in training and test data. For this exercise you can
|
||||
either write your own code or use for example the function for
|
||||
splitting training data provided by the library \textbf{Scikit-Learn} (make
|
||||
sure you have installed it). This function is called
|
||||
$train\_test\_split$. \textbf{You should present a critical discussion of why and how you have scaled or not scaled the data}.
|
||||
|
||||
It is normal in essentially all Machine Learning studies to split the
|
||||
data in a training set and a test set (eventually also an additional
|
||||
validation set). There
|
||||
is no explicit recipe for how much data should be included as training
|
||||
data and say test data. An accepted rule of thumb is to use
|
||||
approximately $2/3$ to $4/5$ of the data as training data.
|
||||
|
||||
You can easily reuse the solutions to your exercises from week 35 and week 36.
|
||||
See also the lecture slides from week 35 and week 36.
|
||||
|
||||
\paragraph{Part c): Bias-variance trade-off and resampling techniques.}
|
||||
Our aim here is to study the bias-variance trade-off by implementing the \textbf{bootstrap} resampling technique.
|
||||
|
||||
With a code which does OLS and includes resampling techniques,
|
||||
we will now discuss the bias-variance trade-off in the context of
|
||||
continuous predictions such as regression. However, many of the
|
||||
intuitions and ideas discussed here also carry over to classification
|
||||
tasks and basically all Machine Learning algorithms.
|
||||
|
||||
Before you perform an analysis of the bias-variance trade-off on your test data, make
|
||||
first a figure similar to Fig.~2.11 of Hastie, Tibshirani, and
|
||||
Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to
|
||||
indicate possible regions of low/high bias and variance. You will most likely not get an
|
||||
equally smooth curve!
|
||||
|
||||
With this result we move on to the bias-variance trade-off analysis.
|
||||
|
||||
Consider a
|
||||
dataset $\mathcal{L}$ consisting of the data
|
||||
$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$.
|
||||
|
||||
As in part a), we assume that the true data is generated from a noisy model
|
||||
|
||||
\[
|
||||
\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon}.
|
||||
\]
|
||||
|
||||
Here $\epsilon$ is normally distributed with mean zero and standard
|
||||
deviation $\sigma^2$.
|
||||
|
||||
In our derivation of the ordinary least squares method we defined then
|
||||
an approximation to the function $f$ in terms of the parameters
|
||||
$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model,
|
||||
that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$.
|
||||
|
||||
The parameters $\bm{\beta}$ are in turn found by optimizing the means
|
||||
squared error via the so-called cost function
|
||||
|
||||
\[
|
||||
C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right].
|
||||
\]
|
||||
Here the expected value $\mathbb{E}$ is the sample value.
|
||||
|
||||
Show that you can rewrite this in terms of a term which contains the variance of the model itself (the so-called variance term), a
|
||||
term which measures the deviation from the true data and the mean value of the model (the bias term) and finally the variance of the noise.
|
||||
That is, show that
|
||||
\[
|
||||
\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=(\mathrm{Bias}[\tilde{y}])^2+\mathrm{var}[\tilde{f}]+\sigma^2,
|
||||
\]
|
||||
with
|
||||
\[
|
||||
(\mathrm{Bias}[\tilde{y}])^2=\left(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right]\right)^2,
|
||||
\]
|
||||
and
|
||||
\[
|
||||
\mathrm{var}[\tilde{f}]=\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2.
|
||||
\]
|
||||
The answer to this exercise should be included in the theory part of the report.
|
||||
Explain what the terms mean and discuss their interpretations.
|
||||
|
||||
Perform then a bias-variance analysis of the Franke function by
|
||||
studying the MSE value as function of the complexity of your model.
|
||||
|
||||
Discuss the bias and variance trade-off as function
|
||||
of your model complexity (the degree of the polynomial) and the number
|
||||
of data points, and possibly also your training and test data using the \textbf{bootstrap} resampling method.
|
||||
You can follow the code example in the jupyter-book at \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html\#the-bias-variance-tradeoff}}.
|
||||
|
||||
\paragraph{Part d): Cross-validation as resampling techniques, adding more complexity.}
|
||||
The aim here is to write your own code for another widely popular
|
||||
resampling technique, the so-called cross-validation method. Again,
|
||||
before you start with cross-validation approach, you should scale your
|
||||
data if you think this is needed.
|
||||
|
||||
Implement the $k$-fold cross-validation algorithm (write your own
|
||||
code) and evaluate again the MSE function resulting
|
||||
from the test folds. You can compare your own code with that from
|
||||
\textbf{Scikit-Learn} if needed.
|
||||
|
||||
Compare the MSE you get from your cross-validation code with the one
|
||||
you got from your \textbf{bootstrap} code. Comment your results. Try $5-10$
|
||||
folds. You can also compare your own cross-validation code with the
|
||||
one provided by \textbf{Scikit-Learn}.
|
||||
|
||||
\paragraph{Part e): Ridge Regression on the Franke function with resampling.}
|
||||
Write your own code for the Ridge method, either using matrix
|
||||
inversion or the singular value decomposition as done in the previous
|
||||
exercise. Perform the same bootstrap analysis as in the
|
||||
part c) (for the same polynomials) and the cross-validation in part d) but now for different values of $\lambda$. Compare and
|
||||
analyze your results with those obtained in parts b-d). Study the
|
||||
dependence on $\lambda$.
|
||||
|
||||
Study also the bias-variance trade-off as function of various values of
|
||||
the parameter $\lambda$. For the bias-variance trade-off, use the \textbf{bootstrap} resampling method. Comment your results.
|
||||
|
||||
\paragraph{Part f): Lasso Regression on the Franke function with resampling.}
|
||||
This exercise is essentially a repeat of the previous two ones, but now
|
||||
with Lasso regression. Write either your own code (difficult and optional) or, in this case,
|
||||
you can also use the functionalities of \textbf{Scikit-Learn} (recommended).
|
||||
Give a
|
||||
critical discussion of the three methods and a judgement of which
|
||||
model fits the data best. Perform here as well an analysis of the bias-variance trade-off using the \textbf{bootstrap} resampling technique and an analysis of the mean squared error using cross-validation.
|
||||
|
||||
\paragraph{Part g): Analysis of real data.}
|
||||
With our codes functioning and having been tested properly on a
|
||||
simpler function we are now ready to look at real data. We will
|
||||
essentially repeat in this exercise what was done in exercises 1-5. However, we
|
||||
need first to download the data and prepare properly the inputs to our
|
||||
codes. We are going to download digital terrain data from the website
|
||||
\href{{https://earthexplorer.usgs.gov/}}{\nolinkurl{https://earthexplorer.usgs.gov/}},
|
||||
|
||||
Or, if you prefer, we have placed selected datafiles at \href{{https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles}}{\nolinkurl{https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles}}
|
||||
|
||||
In order to obtain data for a specific region, you need to register as
|
||||
a user (free) at this website and then decide upon which area you want
|
||||
to fetch the digital terrain data from. In order to be able to read
|
||||
the data properly, you need to specify that the format should be \textbf{SRTM
|
||||
Arc-Second Global} and download the data as a \textbf{GeoTIF} file. The
|
||||
files are then stored in \emph{tif} format which can be imported into a
|
||||
Python program using
|
||||
|
||||
|
||||
|
||||
\begin{verbatim}
|
||||
scipy.misc.imread
|
||||
|
||||
\end{verbatim}
|
||||
|
||||
|
||||
Here is a simple part of a Python code which reads and plots the data
|
||||
from such files
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
\begin{verbatim}
|
||||
import numpy as np
|
||||
from imageio import imread
|
||||
import matplotlib.pyplot as plt
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
from matplotlib import cm
|
||||
|
||||
# Load the terrain
|
||||
terrain1 = imread('SRTM_data_Norway_1.tif')
|
||||
# Show the terrain
|
||||
plt.figure()
|
||||
plt.title('Terrain over Norway 1')
|
||||
plt.imshow(terrain1, cmap='gray')
|
||||
plt.xlabel('X')
|
||||
plt.ylabel('Y')
|
||||
plt.show()
|
||||
|
||||
\end{verbatim}
|
||||
|
||||
|
||||
If you should have problems in downloading the digital terrain data,
|
||||
we provide two examples under the data folder of project 1. One is
|
||||
from a region close to Stavanger in Norway and the other Møsvatn
|
||||
Austfjell, again in Norway.
|
||||
Feel free to produce your own terrain data.
|
||||
|
||||
Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example \href{{https://www.kaggle.com/datasets}}{kaggle.com} for examples.
|
||||
|
||||
Our final part deals with the parameterization of your digital terrain
|
||||
data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial
|
||||
approximation and cross-validation as resampling technique to evaluate which
|
||||
model fits the data best.
|
||||
|
||||
At the end, you should present a critical evaluation of your results
|
||||
and discuss the applicability of these regression methods to the type
|
||||
of data presented here (either the terrain data we propose or other data sets).
|
||||
|
||||
\subsection*{Background literature}
|
||||
|
||||
\begin{enumerate}
|
||||
\item For a discussion and derivation of the variances and mean squared errors using linear regression, see the \href{{https://arxiv.org/abs/1509.09169}}{Lecture notes on ridge regression by Wessel N. van Wieringen}
|
||||
|
||||
\item The textbook of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}, chapters 3 and 7 are the most relevant ones for the analysis here.
|
||||
\end{enumerate}
|
||||
|
||||
\noindent
|
||||
\subsection*{Introduction to numerical projects}
|
||||
|
||||
Here follows a brief recipe and recommendation on how to answer the various questions when preparing your answers.
|
||||
|
||||
\begin{itemize}
|
||||
\item Give a short description of the nature of the problem and the eventual numerical methods you have used.
|
||||
|
||||
\item Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.
|
||||
|
||||
\item Include the source code of your program. Comment your program properly. You should have the code at your GitHub/GitLab link. You can also place the code in an appendix of your report.
|
||||
|
||||
\item If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.
|
||||
|
||||
\item Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.
|
||||
|
||||
\item Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.
|
||||
|
||||
\item Try to give an interpretation of you results in your answers to the problems.
|
||||
|
||||
\item Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.
|
||||
|
||||
\item Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.
|
||||
\end{itemize}
|
||||
|
||||
\noindent
|
||||
\subsection*{Format for electronic delivery of report and programs}
|
||||
|
||||
The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008, Julia or Python. The following prescription should be followed when preparing the report:
|
||||
|
||||
@@ -1,3 +1,462 @@
|
||||
TITLE: Project 1 on Machine Learning, deadline October 7, 2022
|
||||
AUTHOR: "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" at University of Oslo, Norway
|
||||
DATE: today
|
||||
|
||||
|
||||
|
||||
===== Regression analysis and resampling methods =====
|
||||
|
||||
|
||||
|
||||
The main aim of this project is to study in more detail various
|
||||
regression methods, including the Ordinary Least Squares (OLS) method.
|
||||
In addition to the scientific part, in this course we want also to
|
||||
give you an experience in writing scientific reports. The format for
|
||||
the delivery of your answers is namely that of a scientific report. At
|
||||
for example
|
||||
URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md"
|
||||
we detail how to write a report. Furthermore, at
|
||||
URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/"
|
||||
you can find examples of previous reports. How to write reports will
|
||||
also be discussed during lectures and at the various lab sessions.
|
||||
|
||||
|
||||
_A small recommendation when developing the codes here_. Instead of
|
||||
jumping on to the two-dimensional function described below, we
|
||||
recommend to do the code development and testing with a simpler
|
||||
one-dimensional function, similar to those discussed in the exercises
|
||||
of week 35. A simple test, as discussed during the lectures the first
|
||||
two weeks is to set the design matrix equal to the identity
|
||||
matrix. Then your model should give a mean square error which is exactly equal to zero.
|
||||
When you are sure that your codes function well, you can then replace
|
||||
the one-dimensional test function with the two-dimensional _Franke_ function
|
||||
discussed here.
|
||||
|
||||
The Franke function serves as a stepping stone towards the analysis of
|
||||
real topographic data. The latter is the last part of this project.
|
||||
|
||||
|
||||
=== Description of two-dimensional function ===
|
||||
|
||||
We will first study how to fit polynomials to a specific
|
||||
two-dimensional function called "Franke's
|
||||
function":"http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf". This
|
||||
is a function which has been widely used when testing various
|
||||
interpolation and fitting algorithms. Furthermore, after having
|
||||
established the model and the method, we will employ resamling
|
||||
techniques such as cross-validation and/or bootstrap in order to perform a
|
||||
proper assessment of our models. We will also study in detail the
|
||||
so-called Bias-Variance trade off.
|
||||
|
||||
|
||||
The Franke function, which is a weighted sum of four exponentials reads as follows
|
||||
!bt
|
||||
\begin{align*}
|
||||
f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\
|
||||
&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }.
|
||||
\end{align*}
|
||||
!et
|
||||
|
||||
The function will be defined for $x,y\in [0,1]$. Our first step will
|
||||
be to perform an OLS regression analysis of this function, trying out
|
||||
a polynomial fit with an $x$ and $y$ dependence of the form $[x, y,
|
||||
x^2, y^2, xy, \dots]$. We will also include bootstrap first as a
|
||||
resampling technique. After that we will include the cross-validation
|
||||
technique. As discussed in the lectures for weeks 35 and 36,, we can
|
||||
use a uniform distribution to set up the arrays of values for $x$ and
|
||||
$y$, or as in the example below just a set of fixed values for $x$ and
|
||||
$y$ with a given step size. We will fit a function (for example a
|
||||
polynomial) of $x$ and $y$. Thereafter we will repeat much of the
|
||||
same procedure using the Ridge and Lasso regression methods,
|
||||
introducing thus a dependence on the bias (penalty) $\lambda$.
|
||||
|
||||
Finally we are going to use (real) digital terrain data and try to
|
||||
reproduce these data using the same methods. We will also try to go
|
||||
beyond the second-order polynomials metioned above and explore
|
||||
which polynomial fits the data best.
|
||||
|
||||
|
||||
The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)
|
||||
!bc pycod
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib import cm
|
||||
from matplotlib.ticker import LinearLocator, FormatStrFormatter
|
||||
import numpy as np
|
||||
from random import random, seed
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.gca(projection='3d')
|
||||
|
||||
# Make data.
|
||||
x = np.arange(0, 1, 0.05)
|
||||
y = np.arange(0, 1, 0.05)
|
||||
x, y = np.meshgrid(x,y)
|
||||
|
||||
|
||||
def FrankeFunction(x,y):
|
||||
term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
|
||||
term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
|
||||
term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
|
||||
term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
|
||||
return term1 + term2 + term3 + term4
|
||||
|
||||
|
||||
z = FrankeFunction(x, y)
|
||||
|
||||
# Plot the surface.
|
||||
surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
|
||||
linewidth=0, antialiased=False)
|
||||
|
||||
# Customize the z axis.
|
||||
ax.set_zlim(-0.10, 1.40)
|
||||
ax.zaxis.set_major_locator(LinearLocator(10))
|
||||
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
|
||||
|
||||
# Add a color bar which maps values to colors.
|
||||
fig.colorbar(surf, shrink=0.5, aspect=5)
|
||||
|
||||
plt.show()
|
||||
|
||||
!ec
|
||||
|
||||
|
||||
=== Part a): Paper and pencil part (also as weekly exercise for week 36) ===
|
||||
|
||||
|
||||
This exercise deals with various mean values and variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of "Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer":"https://www.springer.com/gp/book/9780387848570").
|
||||
|
||||
The assumption we have made is
|
||||
that there exists a continuous function $f(\bm{x})$ and a normal distributed error $\bm{\varepsilon}\sim N(0, \sigma^2)$
|
||||
which describes our data
|
||||
!bt
|
||||
\[
|
||||
\bm{y} = f(\bm{x})+\bm{\varepsilon}
|
||||
\]
|
||||
!et
|
||||
|
||||
We then approximate this function $f(\bm{x})$ with our model $\bm{\tilde{y}}$ from the solution of the linear regression equations (ordinary least squares OLS), that is our
|
||||
function $f$ is approximated by $\bm{\tilde{y}}$ where we minimized $(\bm{y}-\bm{\tilde{y}})^2$, with
|
||||
!bt
|
||||
\[
|
||||
\bm{\tilde{y}} = \bm{X}\bm{\beta}.
|
||||
\]
|
||||
!et
|
||||
The matrix $\bm{X}$ is the so-called design or feature matrix.
|
||||
|
||||
|
||||
Show that the expectation value of $\bm{y}$ for a given element $i$
|
||||
!bt
|
||||
\[
|
||||
\mathbb{E}(y_i) =\sum_{j}x_{ij} \beta_j=\mathbf{X}_{i, \ast} \, \bm{\beta},
|
||||
\]
|
||||
!et
|
||||
and that
|
||||
its variance is
|
||||
!bt
|
||||
\[
|
||||
\mbox{Var}(y_i) = \sigma^2.
|
||||
\]
|
||||
!et
|
||||
Hence, $y_i \sim N( \mathbf{X}_{i, \ast} \, \bm{\beta}, \sigma^2)$, that is $\bm{y}$ follows a normal distribution with
|
||||
mean value $\bm{X}\bm{\beta}$ and variance $\sigma^2$.
|
||||
|
||||
With the OLS expressions for the optimal parameters $\bm{\hat{\beta}}$ show that
|
||||
!bt
|
||||
\[
|
||||
\mathbb{E}(\bm{\hat{\beta}}) = \bm{\beta}.
|
||||
\]
|
||||
!et
|
||||
Show finally that the variance of $\bm{\beta}$ is
|
||||
!bt
|
||||
\[
|
||||
\mbox{Var}(\bm{\hat{\beta}}) = \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}.
|
||||
\]
|
||||
!et
|
||||
|
||||
|
||||
We can use the last expression when we define a so-called confidence interval for the parameters $\beta$. .
|
||||
A given parameter $\beta_j$ is given by the diagonal matrix element of the above matrix.
|
||||
|
||||
=== Part b) : Ordinary Least Square (OLS) on the Franke function ===
|
||||
|
||||
We will generate our own dataset for a function
|
||||
$\mathrm{FrankeFunction}(x,y)$ with $x,y \in [0,1]$. The function
|
||||
$f(x,y)$ is the Franke function. You should explore also the addition
|
||||
of an added stochastic noise to this function using the normal
|
||||
distribution $N(0,1)$.
|
||||
|
||||
*Write your own code* (using either a matrix inversion or a singular
|
||||
value decomposition from e.g., _numpy_ ) and perform a standard _ordinary least square regression_
|
||||
analysis using polynomials in $x$ and $y$ up to fifth order.
|
||||
|
||||
Evaluate the mean Squared error (MSE)
|
||||
|
||||
|
||||
!bt
|
||||
\[ MSE(\bm{y},\tilde{\bm{y}}) = \frac{1}{n}
|
||||
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
|
||||
\]
|
||||
!et
|
||||
|
||||
and the $R^2$ score function. If $\tilde{\bm{y}}_i$ is the predicted
|
||||
value of the $i-th$ sample and $y_i$ is the corresponding true value,
|
||||
then the score $R^2$ is defined as
|
||||
|
||||
!bt
|
||||
\[
|
||||
R^2(\bm{y}, \tilde{\bm{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
|
||||
\]
|
||||
!et
|
||||
|
||||
where we have defined the mean value of $\bm{y}$ as
|
||||
|
||||
!bt
|
||||
\[
|
||||
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
|
||||
\]
|
||||
!et
|
||||
|
||||
Plot the resulting scores (MSE and R$^2$) as functions of the polynomial degree (here up to polymial degree five).
|
||||
Plot also the parameters $\beta$ as you increase the order of the polynomial. Comment your results.
|
||||
|
||||
Your code has to include a scaling/centering of the data (for example by
|
||||
subtracting the mean value), and
|
||||
a split of the data in training and test data. For this exercise you can
|
||||
either write your own code or use for example the function for
|
||||
splitting training data provided by the library _Scikit-Learn_ (make
|
||||
sure you have installed it). This function is called
|
||||
$train\_test\_split$. _You should present a critical discussion of why and how you have scaled or not scaled the data_.
|
||||
|
||||
|
||||
It is normal in essentially all Machine Learning studies to split the
|
||||
data in a training set and a test set (eventually also an additional
|
||||
validation set). There
|
||||
is no explicit recipe for how much data should be included as training
|
||||
data and say test data. An accepted rule of thumb is to use
|
||||
approximately $2/3$ to $4/5$ of the data as training data.
|
||||
|
||||
|
||||
You can easily reuse the solutions to your exercises from week 35 and week 36.
|
||||
See also the lecture slides from week 35 and week 36.
|
||||
|
||||
|
||||
=== Part c): Bias-variance trade-off and resampling techniques ===
|
||||
|
||||
Our aim here is to study the bias-variance trade-off by implementing the _bootstrap_ resampling technique.
|
||||
|
||||
With a code which does OLS and includes resampling techniques,
|
||||
we will now discuss the bias-variance trade-off in the context of
|
||||
continuous predictions such as regression. However, many of the
|
||||
intuitions and ideas discussed here also carry over to classification
|
||||
tasks and basically all Machine Learning algorithms.
|
||||
|
||||
Before you perform an analysis of the bias-variance trade-off on your test data, make
|
||||
first a figure similar to Fig. 2.11 of Hastie, Tibshirani, and
|
||||
Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to
|
||||
indicate possible regions of low/high bias and variance. You will most likely not get an
|
||||
equally smooth curve!
|
||||
|
||||
With this result we move on to the bias-variance trade-off analysis.
|
||||
|
||||
Consider a
|
||||
dataset $\mathcal{L}$ consisting of the data
|
||||
$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$.
|
||||
|
||||
As in part a), we assume that the true data is generated from a noisy model
|
||||
|
||||
!bt
|
||||
\[
|
||||
\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon}.
|
||||
\]
|
||||
!et
|
||||
|
||||
Here $\epsilon$ is normally distributed with mean zero and standard
|
||||
deviation $\sigma^2$.
|
||||
|
||||
In our derivation of the ordinary least squares method we defined then
|
||||
an approximation to the function $f$ in terms of the parameters
|
||||
$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model,
|
||||
that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$.
|
||||
|
||||
The parameters $\bm{\beta}$ are in turn found by optimizing the means
|
||||
squared error via the so-called cost function
|
||||
|
||||
!bt
|
||||
\[
|
||||
C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right].
|
||||
\]
|
||||
!et
|
||||
Here the expected value $\mathbb{E}$ is the sample value.
|
||||
|
||||
Show that you can rewrite this in terms of a term which contains the variance of the model itself (the so-called variance term), a
|
||||
term which measures the deviation from the true data and the mean value of the model (the bias term) and finally the variance of the noise.
|
||||
That is, show that
|
||||
!bt
|
||||
\[
|
||||
\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=(\mathrm{Bias}[\tilde{y}])^2+\mathrm{var}[\tilde{f}]+\sigma^2,
|
||||
\]
|
||||
!et
|
||||
with
|
||||
!bt
|
||||
\[
|
||||
(\mathrm{Bias}[\tilde{y}])^2=\left(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right]\right)^2,
|
||||
\]
|
||||
!et
|
||||
and
|
||||
!bt
|
||||
\[
|
||||
\mathrm{var}[\tilde{f}]=\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2.
|
||||
\]
|
||||
!et
|
||||
The answer to this exercise should be included in the theory part of the report.
|
||||
Explain what the terms mean and discuss their interpretations.
|
||||
|
||||
Perform then a bias-variance analysis of the Franke function by
|
||||
studying the MSE value as function of the complexity of your model.
|
||||
|
||||
Discuss the bias and variance trade-off as function
|
||||
of your model complexity (the degree of the polynomial) and the number
|
||||
of data points, and possibly also your training and test data using the _bootstrap_ resampling method.
|
||||
You can follow the code example in the jupyter-book at URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff".
|
||||
|
||||
|
||||
=== Part d): Cross-validation as resampling techniques, adding more complexity ===
|
||||
|
||||
|
||||
The aim here is to write your own code for another widely popular
|
||||
resampling technique, the so-called cross-validation method. Again,
|
||||
before you start with cross-validation approach, you should scale your
|
||||
data if you think this is needed.
|
||||
|
||||
Implement the $k$-fold cross-validation algorithm (write your own
|
||||
code) and evaluate again the MSE function resulting
|
||||
from the test folds. You can compare your own code with that from
|
||||
_Scikit-Learn_ if needed.
|
||||
|
||||
Compare the MSE you get from your cross-validation code with the one
|
||||
you got from your _bootstrap_ code. Comment your results. Try $5-10$
|
||||
folds. You can also compare your own cross-validation code with the
|
||||
one provided by _Scikit-Learn_.
|
||||
|
||||
|
||||
=== Part e): Ridge Regression on the Franke function with resampling ===
|
||||
|
||||
Write your own code for the Ridge method, either using matrix
|
||||
inversion or the singular value decomposition as done in the previous
|
||||
exercise. Perform the same bootstrap analysis as in the
|
||||
part c) (for the same polynomials) and the cross-validation in part d) but now for different values of $\lambda$. Compare and
|
||||
analyze your results with those obtained in parts b-d). Study the
|
||||
dependence on $\lambda$.
|
||||
|
||||
Study also the bias-variance trade-off as function of various values of
|
||||
the parameter $\lambda$. For the bias-variance trade-off, use the _bootstrap_ resampling method. Comment your results.
|
||||
|
||||
=== Part f): Lasso Regression on the Franke function with resampling ===
|
||||
|
||||
This exercise is essentially a repeat of the previous two ones, but now
|
||||
with Lasso regression. Write either your own code (difficult and optional) or, in this case,
|
||||
you can also use the functionalities of _Scikit-Learn_ (recommended).
|
||||
Give a
|
||||
critical discussion of the three methods and a judgement of which
|
||||
model fits the data best. Perform here as well an analysis of the bias-variance trade-off using the _bootstrap_ resampling technique and an analysis of the mean squared error using cross-validation.
|
||||
|
||||
=== Part g): Analysis of real data ===
|
||||
|
||||
With our codes functioning and having been tested properly on a
|
||||
simpler function we are now ready to look at real data. We will
|
||||
essentially repeat in this exercise what was done in exercises 1-5. However, we
|
||||
need first to download the data and prepare properly the inputs to our
|
||||
codes. We are going to download digital terrain data from the website
|
||||
URL:"https://earthexplorer.usgs.gov/",
|
||||
|
||||
Or, if you prefer, we have placed selected datafiles at URL:"https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2022/Project1/DataFiles"
|
||||
|
||||
In order to obtain data for a specific region, you need to register as
|
||||
a user (free) at this website and then decide upon which area you want
|
||||
to fetch the digital terrain data from. In order to be able to read
|
||||
the data properly, you need to specify that the format should be _SRTM
|
||||
Arc-Second Global_ and download the data as a _GeoTIF_ file. The
|
||||
files are then stored in *tif* format which can be imported into a
|
||||
Python program using
|
||||
|
||||
!bc pycod
|
||||
scipy.misc.imread
|
||||
!ec
|
||||
|
||||
Here is a simple part of a Python code which reads and plots the data
|
||||
from such files
|
||||
|
||||
!bc pycod
|
||||
import numpy as np
|
||||
from imageio import imread
|
||||
import matplotlib.pyplot as plt
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
from matplotlib import cm
|
||||
|
||||
# Load the terrain
|
||||
terrain1 = imread('SRTM_data_Norway_1.tif')
|
||||
# Show the terrain
|
||||
plt.figure()
|
||||
plt.title('Terrain over Norway 1')
|
||||
plt.imshow(terrain1, cmap='gray')
|
||||
plt.xlabel('X')
|
||||
plt.ylabel('Y')
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
If you should have problems in downloading the digital terrain data,
|
||||
we provide two examples under the data folder of project 1. One is
|
||||
from a region close to Stavanger in Norway and the other Møsvatn
|
||||
Austfjell, again in Norway.
|
||||
Feel free to produce your own terrain data.
|
||||
|
||||
|
||||
Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example "kaggle.com":"https://www.kaggle.com/datasets" for examples.
|
||||
|
||||
|
||||
Our final part deals with the parameterization of your digital terrain
|
||||
data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial
|
||||
approximation and cross-validation as resampling technique to evaluate which
|
||||
model fits the data best.
|
||||
|
||||
At the end, you should present a critical evaluation of your results
|
||||
and discuss the applicability of these regression methods to the type
|
||||
of data presented here (either the terrain data we propose or other data sets).
|
||||
|
||||
|
||||
|
||||
|
||||
===== Background literature =====
|
||||
|
||||
o For a discussion and derivation of the variances and mean squared errors using linear regression, see the "Lecture notes on ridge regression by Wessel N. van Wieringen":"https://arxiv.org/abs/1509.09169"
|
||||
|
||||
o The textbook of "Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer":"https://www.springer.com/gp/book/9780387848570", chapters 3 and 7 are the most relevant ones for the analysis here.
|
||||
|
||||
===== Introduction to numerical projects =====
|
||||
|
||||
Here follows a brief recipe and recommendation on how to answer the various questions when preparing your answers.
|
||||
|
||||
|
||||
* Give a short description of the nature of the problem and the eventual numerical methods you have used.
|
||||
|
||||
* Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.
|
||||
|
||||
* Include the source code of your program. Comment your program properly. You should have the code at your GitHub/GitLab link. You can also place the code in an appendix of your report.
|
||||
|
||||
* If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.
|
||||
|
||||
* Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.
|
||||
|
||||
* Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.
|
||||
|
||||
* Try to give an interpretation of you results in your answers to the problems.
|
||||
|
||||
* Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.
|
||||
|
||||
* Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -51,5 +510,3 @@ encompass communities of developers in the thousands or more. And the number
|
||||
of code developers and contributors keeps increasing.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user