Files
FYS-STK4155/doc/Projects/2023/Project2/html/Project2-bs.html
T
Morten Hjorth-Jensen b03bb69d94 update
2023-11-13 06:13:39 +01:00

400 lines
25 KiB
HTML

<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html Project2.do.txt --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=Project2-bs
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/doconce/doconce/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Project 2 on Machine Learning, deadline November 17 (Midnight)">
<title>Project 2 on Machine Learning, deadline November 17 (Midnight)</title>
<!-- Bootstrap style: bootstrap -->
<!-- doconce format html Project2.do.txt --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=Project2-bs -->
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<!-- not necessary
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
-->
<style type="text/css">
/* Add scrollbar to dropdown menus in bootstrap navigation bar */
.dropdown-menu {
height: auto;
max-height: 400px;
overflow-x: hidden;
}
/* Adds an invisible element before each target to offset for the navigation
bar */
.anchor::before {
content:"";
display:block;
height:50px; /* fixed header height for style bootstrap */
margin:-50px 0 0; /* negative fixed header height */
}
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Classification and Regression, from linear and logistic '
'regression to neural networks',
2,
None,
'classification-and-regression-from-linear-and-logistic-regression-to-neural-networks'),
('Part a): Write your own Stochastic Gradient Descent code, '
'first step',
3,
None,
'part-a-write-your-own-stochastic-gradient-descent-code-first-step'),
('Part b): Writing your own Neural Network code',
3,
None,
'part-b-writing-your-own-neural-network-code'),
('Part c): Testing different activation functions',
3,
None,
'part-c-testing-different-activation-functions'),
('Part d): Classification analysis using neural networks',
3,
None,
'part-d-classification-analysis-using-neural-networks'),
('Part e): Write your Logistic Regression code, final step',
3,
None,
'part-e-write-your-logistic-regression-code-final-step'),
('Part f) Critical evaluation of the various algorithms',
3,
None,
'part-f-critical-evaluation-of-the-various-algorithms'),
('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')]}
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="Project2-bs.html">Project 2 on Machine Learning, deadline November 17 (Midnight)</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="#classification-and-regression-from-linear-and-logistic-regression-to-neural-networks" style="font-size: 80%;"><b>Classification and Regression, from linear and logistic regression to neural networks</b></a></li>
<!-- navigation toc: --> <li><a href="#part-a-write-your-own-stochastic-gradient-descent-code-first-step" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part a): Write your own Stochastic Gradient Descent code, first step</a></li>
<!-- navigation toc: --> <li><a href="#part-b-writing-your-own-neural-network-code" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part b): Writing your own Neural Network code</a></li>
<!-- navigation toc: --> <li><a href="#part-c-testing-different-activation-functions" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part c): Testing different activation functions</a></li>
<!-- navigation toc: --> <li><a href="#part-d-classification-analysis-using-neural-networks" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part d): Classification analysis using neural networks</a></li>
<!-- navigation toc: --> <li><a href="#part-e-write-your-logistic-regression-code-final-step" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part e): Write your Logistic Regression code, final step</a></li>
<!-- navigation toc: --> <li><a href="#part-f-critical-evaluation-of-the-various-algorithms" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part f) Critical evaluation of the various algorithms</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>
</ul>
</li>
</ul>
</div>
</div>
</div> <!-- end of navigation bar -->
<div class="container">
<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p> <!-- add vertical space -->
<a name="part0000"></a>
<!-- ------------------- main content ---------------------- -->
<div class="jumbotron">
<center>
<h1>Project 2 on Machine Learning, deadline November 17 (Midnight)</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>Department of Physics, University of Oslo, Norway</b>
</center>
<br>
<center>
<h4>Nov 13, 2023</h4>
</center> <!-- date -->
<br>
</div> <!-- end jumbotron -->
<h2 id="classification-and-regression-from-linear-and-logistic-regression-to-neural-networks" class="anchor">Classification and Regression, from linear and logistic regression to neural networks </h2>
<p>The main aim of this project is to study both classification and
regression problems by developing our own feed-forward neural network
(FFNN) code. We can reuse the regression algorithms studied in project
1. We will also include logistic regression for classification
problems and write our own FFNN code for studying both regression and
classification problems. The codes developed in project 1, including
bootstrap <b>and/or</b> cross-validation as well as the computation of the
mean-squared error and/or the \( R2 \) or the accuracy score
(classification problems) functions can also be utilized in the
present analysis.
</p>
<p>The data sets that we propose here are (the default sets)</p>
<ul>
<li> Regression (fitting a continuous function). In this part you will need to bring back your results from project 1 and compare these with what you get from your Neural Network code to be developed here. The data sets could be
<ol type="a"></li>
<li> A simple one-dimensional function or the Franke function or the terrain data from project 1, or data sets your propose. It could be a simpler function than the Franke function. We recommend testing a simpler function (see below). But if you wish to try more complex function, feel free to do so.</li>
</ol>
<li> Classification. Here you will also need to develop a Logistic regression code that you will use to compare with the Neural Network code. The data set we propose are the so-called <a href="https://www.kaggle.com/uciml/breast-cancer-wisconsin-data" target="_self">Wisconsin Breat Cancer Data</a> data set of images representing various features of tumors. These are discussed intensively in the lecture notes, see for example the slides from <a href="https://compphysics.github.io/MachineLearning/doc/pub/week41/html/week41.html" target="_self">week 41</a>. A longer explanation with links to the scientific literature can be found at the <a href="https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Diagnostic%29" target="_self">Machine Learning repository of the University of California at Irvine</a>. Feel free to consult this site and the pertinent literature.</li>
</ul>
<p>You can find more information about this at the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html" target="_self">Scikit-Learn site</a> or at the <a href="https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)" target="_self">University of California at Irvine</a>. </p>
<p>However, if you would like to study other data sets, feel free to
propose other sets. What we list here are mere suggestions from our
side. If you opt for another data set, consider using a set which has
been studied in the scientific literature. This makes it easier for
you to compare and analyze your results. Comparing with existing
results from the scientific literature is also an essential element of
the scientific discussion. The University of California at Irvine
with its Machine Learning repository at
<a href="https://archive.ics.uci.edu/ml/index.php" target="_self"><tt>https://archive.ics.uci.edu/ml/index.php</tt></a> is an excellent site to
look up for examples and
inspiration. <a href="https://www.kaggle.com/" target="_self">Kaggle.com</a> is an equally
interesting site. Feel free to explore these sites.
</p>
<p>We will start with a regression problem and we will reuse our codes from project 1 starting with writing our own Stochastic Gradient Descent (SGD) code. </p>
<h3 id="part-a-write-your-own-stochastic-gradient-descent-code-first-step" class="anchor">Part a): Write your own Stochastic Gradient Descent code, first step </h3>
<p>In order to get started, we will now replace in our standard ordinary
least squares (OLS) and Ridge regression codes (from project 1) the
matrix inversion algorithm with our own gradient descent (GD) and SGD
codes. You can use the Franke function or the terrain data from
project 1. <b>However, we recommend using a simpler function like</b>
\( f(x)=a_0+a_1x+a_2x^2 \) or higher-order one-dimensional polynomials.
You can obviously test your final codes against for example the Franke
function.
</p>
<p>You should include in your analysis of the GD and SGD codes the following elements</p>
<ol>
<li> A plain gradient descent with a fixed learning rate (you will need to tune it) using the analytical expression for the gradient.</li>
<li> Add momentum to the plain GD code and compare convergence with a fixed learning rate (you may need to tune the learning rate). Keep using the analytical expression for the gradient.</li>
<li> Repeat these steps for stochastic gradient descent with mini batches and a given number of epochs. Use a tunable learning rate as discussed in the lectures from weeks 39 and 40. Discuss the results as functions of the various parameters (size of batches, number of epochs etc). Use the analytical gradient.</li>
<li> Implement the Adagrad method in order to tune the learning rate. Do this with and without momentum for plain gradient descent and SGD.</li>
<li> Add RMSprop and Adam to your library of methods for tuning the learning rate.</li>
</ol>
<p>The lecture notes from <a href="https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html" target="_self">weeks 39 and 40contain more
details</a> and code examples. Feel free to use these examples.
</p>
<ol>
<li> Replace thereafter your analytical gradient with either <b>Autograd</b> or <b>JAX</b></li>
</ol>
<p>In summary, you should
perform an analysis of the results for OLS and Ridge regression as
function of the chosen learning rates, the number of mini-batches and
epochs as well as algorithm for scaling the learning rate. You can
also compare your own results with those that can be obtained using
for example <b>Scikit-Learn</b>'s various SGD options. Discuss your
results. For Ridge regression you need now to study the results as functions of the hyper-parameter \( \lambda \) and
the learning rate \( \eta \). Discuss your results.
</p>
<p>You will need your SGD code for the setup of the Neural Network and
Logistic Regression codes. You will find the Python <a href="https://seaborn.pydata.org/generated/seaborn.heatmap.html" target="_self">Seaborn
package</a>
useful when plotting the results as function of the learning rate
\( \eta \) and the hyper-parameter \( \lambda \) when you use Ridge
regression.
</p>
<p>We recommend reading chapter 8 on optimization from the textbook of <a href="https://www.deeplearningbook.org/" target="_self">Goodfellow, Bengio and Courville</a>. This chapter contains many useful insights and discussions on the optimization part of machine learning.</p>
<h3 id="part-b-writing-your-own-neural-network-code" class="anchor">Part b): Writing your own Neural Network code </h3>
<p>Your aim now, and this is the central part of this project, is to
write your own Feed Forward Neural Network code implementing the back
propagation algorithm discussed in the lecture slides from <a href="https://compphysics.github.io/MachineLearning/doc/pub/week41/html/week40.html" target="_self">week 40</a> and
<a href="https://compphysics.github.io/MachineLearning/doc/pub/week41/html/week41.html" target="_self">week 41</a>.
</p>
<p>We will focus on a regression problem first and study either the simple second-order polynomial from part a) or the
Franke function or terrain data (or both or other data sets) from
project 1.
</p>
<p>Discuss again your choice of cost function.</p>
<p>Write an FFNN code for regression with a flexible number of hidden
layers and nodes using the Sigmoid function as activation function for
the hidden layers. Initialize the weights using a normal
distribution. How would you initialize the biases? And which
activation function would you select for the final output layer?
</p>
<p>Train your network and compare the results with those from your OLS and Ridge Regression codes from project 1 if you use the Franke function or the terrain data.
You should test your results against a similar code using <b>Scikit-Learn</b> (see the examples in the above lecture notes from week 41) or <b>tensorflow/keras</b>.
</p>
<p>Comment your results and give a critical discussion of the results
obtained with the Linear Regression code and your own Neural Network
code.
Make an analysis of the regularization parameters and the learning rates employed to find the optimal MSE and \( R2 \) scores.
</p>
<p>A useful reference on the back progagation algorithm is <a href="http://neuralnetworksanddeeplearning.com/" target="_self">Nielsen's
book</a>. It is an excellent
read.
</p>
<h3 id="part-c-testing-different-activation-functions" class="anchor">Part c): Testing different activation functions </h3>
<p>You should now also test different activation functions for the hidden layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and discuss your results. You may also study the way you initialize your weights and biases.</p>
<h3 id="part-d-classification-analysis-using-neural-networks" class="anchor">Part d): Classification analysis using neural networks </h3>
<p>With a well-written code it should now be easy to change the
activation function for the output layer.
</p>
<p>Here we will change the cost function for our neural network code
developed in parts b) and c) in order to perform a classification analysis.
</p>
<p>We will here study the Wisconsin Breast Cancer data set. This is a typical binary classification problem with just one single output, either True or Fale, \( 0 \) or \( 1 \) etc.
You find more information about this at the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html" target="_self">Scikit-Learn
site</a> or at the <a href="https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)" target="_self">University of California
at Irvine</a>.
</p>
<p>To measure the performance of our classification problem we use the
so-called <em>accuracy</em> score. The accuracy is as you would expect just
the number of correctly guessed targets \( t_i \) divided by the total
number of targets, that is
</p>
$$
\text{Accuracy} = \frac{\sum_{i=1}^n I(t_i = y_i)}{n} ,
$$
<p>where \( I \) is the indicator function, \( 1 \) if \( t_i = y_i \) and \( 0 \)
otherwise if we have a binary classification problem. Here \( t_i \)
represents the target and \( y_i \) the outputs of your FFNN code and \( n \) is simply the number of targets \( t_i \).
</p>
<p>Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter \( \lambda \) (as you did in Ridge Regression), various activation functions, number of hidden layers and nodes and activation functions. </p>
<p>As stated in the introduction, it can also be useful to study other
datasets.
</p>
<p>Again, we strongly recommend that you compare your own neural Network
code for classification and pertinent results against a similar code using <b>Scikit-Learn</b> or <b>tensorflow/keras</b> or <b>pytorch</b>.
</p>
<h3 id="part-e-write-your-logistic-regression-code-final-step" class="anchor">Part e): Write your Logistic Regression code, final step </h3>
<p>Finally, we want to compare the FFNN code we have developed with
Logistic regression, that is we wish to compare our neural network
classification results with the results we can obtain with another
method.
</p>
<p>Define your cost function and the design matrix before you start writing your code.
Write thereafter a Logistic regression code using your SGD algorithm. You can also use standard gradient descent in this case, with a learning rate as hyper-parameter.
Study the results as functions of the chosen learning rates.
Add also an \( l_2 \) regularization parameter \( \lambda \). Compare your results with those from your FFNN code as well as those obtained using <b>Scikit-Learn</b>'s logistic regression functionality.
</p>
<p>The weblink here <a href="https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3" target="_self"><tt>https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3</tt></a>compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article. </p>
<h3 id="part-f-critical-evaluation-of-the-various-algorithms" class="anchor">Part f) Critical evaluation of the various algorithms </h3>
<p>After all these glorious calculations, you should now summarize the
various algorithms and come with a critical evaluation of their pros
and cons. Which algorithm works best for the regression case and which
is best for the classification case. These codes can also be part of
your final project 3, but now applied to other data sets.
</p>
<h2 id="background-literature" class="anchor">Background literature </h2>
<ol>
<li> The text of Michael Nielsen is highly recommended, see <a href="http://neuralnetworksanddeeplearning.com/" target="_self">Nielsen's book</a>. It is an excellent read.</li>
<li> <a href="https://arxiv.org/abs/1803.08823" target="_self">Mehta et al, arXiv 1803.08823</a>, <em>A high-bias, low-variance introduction to Machine Learning for physicists</em>, ArXiv:1803.08823.</li>
</ol>
<li> <a href="https://www.deeplearningbook.org/" target="_self">Goodfellow, Bengio and Courville</a>, <em>Deep Learning</em>.
<h2 id="introduction-to-numerical-projects" class="anchor">Introduction to numerical projects </h2>
<p>Here follows a brief recipe and recommendation on how to write a report for each
project.
</p>
</li>
<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.</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 or Python. The following prescription should be followed when preparing the report:</p>
<ul>
<li> Use Canvas to hand in your projects, log in at <a href="https://www.uio.no/english/services/it/education/canvas/" target="_self"><tt>https://www.uio.no/english/services/it/education/canvas/</tt></a> with your normal UiO username and password.</li>
<li> Upload <b>only</b> the report file or the link to your GitHub/GitLab or similar typo of repos! For the source code file(s) you have developed please provide us with your link to your GitHub/GitLab or similar domain. The report file should include all of your discussions and a list of the codes you have developed. Do not include library files which are available at the course homepage, unless you have made specific changes to them.</li>
<li> In your GitHub/GitLab or similar repository, please include a folder which contains selected results. These can be in the form of output from your code for a selected set of runs and input parameters.</li>
</ul>
<p>Finally,
we encourage you to collaborate. Optimal working groups consist of
2-3 students. You can then hand in a common report.
</p>
<p>
<!-- navigation buttons at the bottom of the page -->
<ul class="pagination">
<li class="active"><a href="._Project2-bs000.html">1</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
</div> <!-- end container -->
<!-- include javascript, jQuery *first* -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<!-- Bootstrap footer
<footer>
<a href="https://..."><img width="250" align=right src="https://..."></a>
</footer>
-->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2023, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>