update project 2

This commit is contained in:
Morten Hjorth-Jensen
2025-10-13 08:26:45 +02:00
parent 895a2f10c5
commit 56645d23fe
10 changed files with 4149 additions and 112 deletions
@@ -0,0 +1,587 @@
<!--
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 10 (Midnight)">
<title>Project 2 on Machine Learning, deadline November 10 (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': [('Deliverables', 2, None, 'deliverables'),
('Preamble: Note on writing reports, using reference material, '
'AI and other tools',
3,
None,
'preamble-note-on-writing-reports-using-reference-material-ai-and-other-tools'),
('Classification and Regression, writing our own neural network '
'code',
2,
None,
'classification-and-regression-writing-our-own-neural-network-code'),
('Part a): Analytical warm-up',
3,
None,
'part-a-analytical-warm-up'),
('Reminder about the gradient machinery from project 1',
3,
None,
'reminder-about-the-gradient-machinery-from-project-1'),
('Part b): Writing your own Neural Network code',
3,
None,
'part-b-writing-your-own-neural-network-code'),
('Part c): Testing against other software libraries',
3,
None,
'part-c-testing-against-other-software-libraries'),
('Part d): Testing different activation functions and depths of '
'the neural network',
3,
None,
'part-d-testing-different-activation-functions-and-depths-of-the-neural-network'),
('Part e): Testing different norms',
3,
None,
'part-e-testing-different-norms'),
('Part f): Classification analysis using neural networks',
3,
None,
'part-f-classification-analysis-using-neural-networks'),
('Part g) Critical evaluation of the various algorithms',
3,
None,
'part-g-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 10 (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="#deliverables" style="font-size: 80%;"><b>Deliverables</b></a></li>
<!-- navigation toc: --> <li><a href="#preamble-note-on-writing-reports-using-reference-material-ai-and-other-tools" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Preamble: Note on writing reports, using reference material, AI and other tools</a></li>
<!-- navigation toc: --> <li><a href="#classification-and-regression-writing-our-own-neural-network-code" style="font-size: 80%;"><b>Classification and Regression, writing our own neural network code</b></a></li>
<!-- navigation toc: --> <li><a href="#part-a-analytical-warm-up" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part a): Analytical warm-up</a></li>
<!-- navigation toc: --> <li><a href="#reminder-about-the-gradient-machinery-from-project-1" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Reminder about the gradient machinery from project 1</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-against-other-software-libraries" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part c): Testing against other software libraries</a></li>
<!-- navigation toc: --> <li><a href="#part-d-testing-different-activation-functions-and-depths-of-the-neural-network" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part d): Testing different activation functions and depths of the neural network</a></li>
<!-- navigation toc: --> <li><a href="#part-e-testing-different-norms" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part e): Testing different norms</a></li>
<!-- navigation toc: --> <li><a href="#part-f-classification-analysis-using-neural-networks" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part f): Classification analysis using neural networks</a></li>
<!-- navigation toc: --> <li><a href="#part-g-critical-evaluation-of-the-various-algorithms" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part g) 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 10 (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>University of Oslo, Norway</b>
</center>
<br>
<center>
<h4>October 14, 2025</h4>
</center> <!-- date -->
<br>
</div> <!-- end jumbotron -->
<h2 id="deliverables" class="anchor">Deliverables </h2>
<p>First, join a group in canvas with your group partners. Pick an avaliable group for Project 2 in the <b>People</b> page.</p>
<p>In canvas, deliver as a group and include:</p>
<ul>
<li> A PDF of your report which follows the guidelines covered below and in the week 39 exercises. Additional requirements include:</li>
<ul>
<li> It should be around 5000 words, use the word counter in Overleaf for this. This often corresponds to 10-12 pages. References and appendices are excluded from the word count</li>
<li> It should include around 10-15 figures. You can include more figures in appendices and/or as supplemental material in your repository.</li>
</ul>
<li> A comment linking to your github repository (or folder in one of your github repositories) for this project. The repository must include</li>
</ul>
<p>A PDF file of the report</p>
<ul>
<li> A folder named Code, where you put python files for your functions and notebooks for reproducing your results. Remember to use a seed for generating random data and for train-test splits when generating final results.</li>
<li> A README file with the name of the group members</li>
<li> a short description of the project</li>
<li> a description of how to install the required packages to run your code from a requirements.txt file or similar (such as a plain text description) names and descriptions of the various notebooks in the Code folder and the results they produce</li>
</ul>
<h3 id="preamble-note-on-writing-reports-using-reference-material-ai-and-other-tools" class="anchor">Preamble: Note on writing reports, using reference material, AI and other tools </h3>
<p>We want you to answer the three different projects by handing in
reports written like a standard scientific/technical report. The links
at
https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects
contain more information. There you can find examples of previous
reports, the projects themselves, how we grade reports etc. How to
write reports will also be discussed during the various lab
sessions. Please do ask us if you are in doubt.
</p>
<p>When using codes and material from other sources, you should refer to
these in the bibliography of your report, indicating wherefrom you for
example got the code, whether this is from the lecture notes,
softwares like Scikit-Learn, TensorFlow, PyTorch or other
sources. These sources should always be cited correctly. How to cite
some of the libraries is often indicated from their corresponding
GitHub sites or websites, see for example how to cite Scikit-Learn at
https://scikit-learn.org/dev/about.html.
</p>
<p>We enocurage you to use tools like ChatGPT or similar in writing the
report. If you use for example ChatGPT, please do cite it properly and
include (if possible) your questions and answers as an addition to the
report. This can be uploaded to for example your website,
GitHub/GitLab or similar as supplemental material.
</p>
<p>If you would like to study other data sets, feel free to propose other
sets. What we have proposed 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
https://archive.ics.uci.edu/ml/index.php is an excellent site to look
up for examples and inspiration. Kaggle.com is an equally interesting
site. Feel free to explore these sites.
</p>
<h2 id="classification-and-regression-writing-our-own-neural-network-code" class="anchor">Classification and Regression, writing our own neural network code </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. The exercises from week 41 and 42 (see <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html</tt></a> and <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html</tt></a>) as well as the lecture material from the same weeks (see <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html</tt></a> and <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html</tt></a>) should contain enough information for you to get started with writing your own code.
</p>
<p>We will also reuse our codes on gradient descent methods from project 1.</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> The simple one-dimensional function Runge function from project 1, that is \( f(x) = \frac{1}{1+25x^2} \). We recommend using a simpler function when developing your neural network code for regression problems. You should however feel free to discuss and study other functions, such as the the two-dimensional Runge function \( f(x,y)=\left[(10x - 5)^2 + (10y - 5)^2 + 1 \right]^{-1} \), or even more complicated two-dimensional functions (see the supplementary material of <a href="https://www.nature.com/articles/s41467-025-61362-4" target="_self"><tt>https://www.nature.com/articles/s41467-025-61362-4</tt></a> for an extensive list of two-dimensional functions).</li>
</ol>
<li> Classification.
<ol type="a"></li>
<li> We will consider the multiclass classification problem given by the full MNIST data set. The one included in <b>scikit-learn</b> is reduced data. The full data set is at <a href="https://www.kaggle.com/datasets/hojjatk/mnist-dataset" target="_self"><tt>https://www.kaggle.com/datasets/hojjatk/mnist-dataset</tt></a>.</li>
</ol>
</ul>
<p>We will start with a regression problem and we will reuse our codes on gradient descent methods from project 1.</p>
<h3 id="part-a-analytical-warm-up" class="anchor">Part a): Analytical warm-up </h3>
<p>When using our gradient machinery from project 1, we will need the expressions for the cost/loss functions and their respective
gradients. The functions whose gradients we need are:
</p>
<ol>
<li> The mean-squared error (MSE) with and without the \( L_1 \) and \( L_2 \) norms (regression problems)</li>
<li> The binary cross entropy (aka log loss) for classification problems with and without \( L_1 \) and \( L_2 \) norms</li>
<li> The multiclass cross entropy cost/loss function (aka Softmax cross entropy or just Softmax loss function)</li>
</ol>
<p>Set up these three cost/loss functions and their respective derivatives and explain the various terms.</p>
<p>We will test three activation functions for our neural network setup, these are the </p>
<ol>
<li> The Sigmoid (aka <b>logit</b>) function,</li>
<li> the RELU function and</li>
<li> the Leaky RELU function</li>
</ol>
<p>Set up their expressions and their first derivatives.
You may consult the lecture notes (with codes and more) from week 42 at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html</tt></a>.
</p>
<h3 id="reminder-about-the-gradient-machinery-from-project-1" class="anchor">Reminder about the gradient machinery from project 1 </h3>
<p>In the setup of a neural network code you will need your gradient descent codes from
project 1. For neural networks we will recommend using stochastic
gradient descent with either the RMSprop or the ADAM algorithms for
updating the learning rates. But you should feel free to try plain gradient descent as well.
</p>
<p>We recommend reading chapter 8 on optimization from the textbook of
Goodfellow, Bengio and Courville at
<a href="https://www.deeplearningbook.org/" target="_self"><tt>https://www.deeplearningbook.org/</tt></a>. This chapter contains many
useful insights and discussions on the optimization part of machine
learning. A useful reference on the back progagation algorithm is
Nielsen's book at <a href="http://neuralnetworksanddeeplearning.com/" target="_self"><tt>http://neuralnetworksanddeeplearning.com/</tt></a>.
</p>
<p>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 \) .
</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 FFNN code implementing the back
propagation algorithm discussed in the lecture slides from week 41 at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html</tt></a> and week 42 at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html</tt></a>.
</p>
<p>We will focus on a regression problem first, using the one-dimensional Runge function</p>
$$
f(x) = \frac{1}{1+25x^2},
$$
<p>from project 1.</p>
<p>Use only the mean-squared error as cost function (no regularization terms) and
write an FFNN code for a regression problem with a flexible number of hidden
layers and nodes using only 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?
And how would you set up your design/feature matrix? Hint: does it have to represent a polynomial approximation as you did in project 1?
</p>
<p>Train your network and compare the results with those from your OLS
regression code from project 1 using the one-dimensional Runge
function. When comparing your neural network code with the OLS
results from project 1, use the same data sets which gave you the best
MSE score. Moreover, use the polynomial order from project 1 that gave you the
best result. Compare these results with your neural network with one
and two hidden layers using \( 50 \) and \( 100 \) hidden nodes, respectively.
</p>
<p>Comment your results and give a critical discussion of the results
obtained with the OLS code from project 1 and your own neural network
code. Make an analysis of the learning rates employed to find the
optimal MSE and \( R2 \) scores. Test both stochastic gradient descent
with RMSprop and ADAM and plain gradient descent with different
learning rates.
</p>
<p>You should, as you did in project 1, scale your data.</p>
<h3 id="part-c-testing-against-other-software-libraries" class="anchor">Part c): Testing against other software libraries </h3>
<p>You should test your results against a similar code using <b>Scikit-Learn</b> (see the examples in the above lecture notes from weeks 41 and 42) or <b>tensorflow/keras</b> or <b>Pytorch</b> (for Pytorch, see Raschka et al.'s text chapters 12 and 13). </p>
<p>Furthermore, you should also test that your derivatives are correctly
calculated using automatic differentiation, using for example the
<b>Autograd</b> library or the <b>JAX</b> library. It is optional to implement
these libraries for the present project. In this project they serve as
useful tests of our derivatives.
</p>
<h3 id="part-d-testing-different-activation-functions-and-depths-of-the-neural-network" class="anchor">Part d): Testing different activation functions and depths of the neural network </h3>
<p>You should also test different activation functions for the hidden
layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and
discuss your results. Test your results as functions of the number of hidden layers and nodes. Do you see signs of overfitting?
It is optional in this project to perform a bias-variance trade-off analysis.
</p>
<h3 id="part-e-testing-different-norms" class="anchor">Part e): Testing different norms </h3>
<p>Finally, still using the one-dimensional Runge function, add now the
hyperparameters \( \lambda \) with the \( L_2 \) and \( L_1 \) norms. Find the
optimal results for the hyperparameters \( \lambda \) and the learning
rates \( \eta \) and neural network architecture and compare the \( L_2 \) results with Ridge regression from
project 1 and the \( L_1 \) results with the Lasso calculations of project 1.
Use again the same data sets and the best results from project 1 in your comparisons.
</p>
<h3 id="part-f-classification-analysis-using-neural-networks" class="anchor">Part f): 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), d) and e) in order to perform a classification
analysis. The classification problem we will study is the multiclass
MNIST problem, see the description of the full data set at
<a href="https://www.kaggle.com/datasets/hojjatk/mnist-dataset" target="_self"><tt>https://www.kaggle.com/datasets/hojjatk/mnist-dataset</tt></a>. We will use the Softmax cross entropy function discussed in a).
The MNIST data set discussed in the lecture notes from week 42 is a downscaled variant of the full dataset.
</p>
<p>Feel free to suggest other data sets. If you find the classic MNIST data set somewhat limited, feel free to try the
MNIST-Fashion data set at for example <a href="https://www.kaggle.com/datasets/zalando-research/fashionmnist" target="_self"><tt>https://www.kaggle.com/datasets/zalando-research/fashionmnist</tt></a>.
</p>
<p>To set up the data set, the following python programs may be useful</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">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> fetch_openml
<span style="color: #408080; font-style: italic"># Fetch the MNIST dataset</span>
mnist <span style="color: #666666">=</span> fetch_openml(<span style="color: #BA2121">&#39;mnist_784&#39;</span>, version<span style="color: #666666">=1</span>, as_frame<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>, parser<span style="color: #666666">=</span><span style="color: #BA2121">&#39;auto&#39;</span>)
<span style="color: #408080; font-style: italic"># Extract data (features) and target (labels)</span>
X <span style="color: #666666">=</span> mnist<span style="color: #666666">.</span>data
y <span style="color: #666666">=</span> mnist<span style="color: #666666">.</span>target
</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>You should consider scaling the data. The Pixel values in MNIST range from 0 to 255. Scaling them to a 0-1 range can improve the performance of some models. That is, you could implement the following scaling</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%;">X <span style="color: #666666">=</span> X <span style="color: #666666">/</span> <span style="color: #666666">255.0</span>
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>And then perform the standard train-test splitting</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">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>, random_state<span style="color: #666666">=42</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>To measure the performance of our classification problem we will 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 \), various activation functions, number of hidden layers and nodes and activation functions. </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>
<p>If you have time, you can use the functionality of <b>scikit-learn</b> and compare your neural network results with those from Logistic regression. This is optional.
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. Your neural network code can implement the equivalent of logistic regression by simply setting the number of hidden layers to zero.
</p>
<p>If you wish to compare with say Logisti Regression from <b>scikit-learn</b>, the following code uses the above data set</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">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
<span style="color: #408080; font-style: italic"># Initialize the model</span>
model <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">&#39;saga&#39;</span>, multi_class<span style="color: #666666">=</span><span style="color: #BA2121">&#39;multinomial&#39;</span>, max_iter<span style="color: #666666">=1000</span>, random_state<span style="color: #666666">=42</span>)
<span style="color: #408080; font-style: italic"># Train the model</span>
model<span style="color: #666666">.</span>fit(X_train, y_train)
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
<span style="color: #408080; font-style: italic"># Make predictions on the test set</span>
y_pred <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(X_test)
<span style="color: #408080; font-style: italic"># Calculate accuracy</span>
accuracy <span style="color: #666666">=</span> accuracy_score(y_test, y_pred)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Model Accuracy: </span><span style="color: #BB6688; font-weight: bold">{</span>accuracy<span style="color: #BB6688; font-weight: bold">:</span><span style="color: #BA2121">.4f</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<h3 id="part-g-critical-evaluation-of-the-various-algorithms" class="anchor">Part g) 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 Nielsen's book at <a href="http://neuralnetworksanddeeplearning.com/" target="_self"><tt>http://neuralnetworksanddeeplearning.com/</tt></a>. It is an excellent read.</li>
<li> Goodfellow, Bengio and Courville, Deep Learning at <a href="https://www.deeplearningbook.org/" target="_self"><tt>https://www.deeplearningbook.org/</tt></a>. Here we recommend chapters 6, 7 and 8</li>
<li> Raschka et al. at <a href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" target="_self"><tt>https://sebastianraschka.com/blog/2022/ml-pytorch-book.html</tt></a>. Here we recommend chapters 11, 12 and 13.</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 write a report for each
project.
</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.</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-2025, "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>
@@ -0,0 +1,587 @@
<!--
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 10 (Midnight)">
<title>Project 2 on Machine Learning, deadline November 10 (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': [('Deliverables', 2, None, 'deliverables'),
('Preamble: Note on writing reports, using reference material, '
'AI and other tools',
3,
None,
'preamble-note-on-writing-reports-using-reference-material-ai-and-other-tools'),
('Classification and Regression, writing our own neural network '
'code',
2,
None,
'classification-and-regression-writing-our-own-neural-network-code'),
('Part a): Analytical warm-up',
3,
None,
'part-a-analytical-warm-up'),
('Reminder about the gradient machinery from project 1',
3,
None,
'reminder-about-the-gradient-machinery-from-project-1'),
('Part b): Writing your own Neural Network code',
3,
None,
'part-b-writing-your-own-neural-network-code'),
('Part c): Testing against other software libraries',
3,
None,
'part-c-testing-against-other-software-libraries'),
('Part d): Testing different activation functions and depths of '
'the neural network',
3,
None,
'part-d-testing-different-activation-functions-and-depths-of-the-neural-network'),
('Part e): Testing different norms',
3,
None,
'part-e-testing-different-norms'),
('Part f): Classification analysis using neural networks',
3,
None,
'part-f-classification-analysis-using-neural-networks'),
('Part g) Critical evaluation of the various algorithms',
3,
None,
'part-g-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 10 (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="#deliverables" style="font-size: 80%;"><b>Deliverables</b></a></li>
<!-- navigation toc: --> <li><a href="#preamble-note-on-writing-reports-using-reference-material-ai-and-other-tools" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Preamble: Note on writing reports, using reference material, AI and other tools</a></li>
<!-- navigation toc: --> <li><a href="#classification-and-regression-writing-our-own-neural-network-code" style="font-size: 80%;"><b>Classification and Regression, writing our own neural network code</b></a></li>
<!-- navigation toc: --> <li><a href="#part-a-analytical-warm-up" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part a): Analytical warm-up</a></li>
<!-- navigation toc: --> <li><a href="#reminder-about-the-gradient-machinery-from-project-1" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Reminder about the gradient machinery from project 1</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-against-other-software-libraries" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part c): Testing against other software libraries</a></li>
<!-- navigation toc: --> <li><a href="#part-d-testing-different-activation-functions-and-depths-of-the-neural-network" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part d): Testing different activation functions and depths of the neural network</a></li>
<!-- navigation toc: --> <li><a href="#part-e-testing-different-norms" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part e): Testing different norms</a></li>
<!-- navigation toc: --> <li><a href="#part-f-classification-analysis-using-neural-networks" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part f): Classification analysis using neural networks</a></li>
<!-- navigation toc: --> <li><a href="#part-g-critical-evaluation-of-the-various-algorithms" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Part g) 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 10 (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>University of Oslo, Norway</b>
</center>
<br>
<center>
<h4>October 14, 2025</h4>
</center> <!-- date -->
<br>
</div> <!-- end jumbotron -->
<h2 id="deliverables" class="anchor">Deliverables </h2>
<p>First, join a group in canvas with your group partners. Pick an avaliable group for Project 2 in the <b>People</b> page.</p>
<p>In canvas, deliver as a group and include:</p>
<ul>
<li> A PDF of your report which follows the guidelines covered below and in the week 39 exercises. Additional requirements include:</li>
<ul>
<li> It should be around 5000 words, use the word counter in Overleaf for this. This often corresponds to 10-12 pages. References and appendices are excluded from the word count</li>
<li> It should include around 10-15 figures. You can include more figures in appendices and/or as supplemental material in your repository.</li>
</ul>
<li> A comment linking to your github repository (or folder in one of your github repositories) for this project. The repository must include</li>
</ul>
<p>A PDF file of the report</p>
<ul>
<li> A folder named Code, where you put python files for your functions and notebooks for reproducing your results. Remember to use a seed for generating random data and for train-test splits when generating final results.</li>
<li> A README file with the name of the group members</li>
<li> a short description of the project</li>
<li> a description of how to install the required packages to run your code from a requirements.txt file or similar (such as a plain text description) names and descriptions of the various notebooks in the Code folder and the results they produce</li>
</ul>
<h3 id="preamble-note-on-writing-reports-using-reference-material-ai-and-other-tools" class="anchor">Preamble: Note on writing reports, using reference material, AI and other tools </h3>
<p>We want you to answer the three different projects by handing in
reports written like a standard scientific/technical report. The links
at
https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects
contain more information. There you can find examples of previous
reports, the projects themselves, how we grade reports etc. How to
write reports will also be discussed during the various lab
sessions. Please do ask us if you are in doubt.
</p>
<p>When using codes and material from other sources, you should refer to
these in the bibliography of your report, indicating wherefrom you for
example got the code, whether this is from the lecture notes,
softwares like Scikit-Learn, TensorFlow, PyTorch or other
sources. These sources should always be cited correctly. How to cite
some of the libraries is often indicated from their corresponding
GitHub sites or websites, see for example how to cite Scikit-Learn at
https://scikit-learn.org/dev/about.html.
</p>
<p>We enocurage you to use tools like ChatGPT or similar in writing the
report. If you use for example ChatGPT, please do cite it properly and
include (if possible) your questions and answers as an addition to the
report. This can be uploaded to for example your website,
GitHub/GitLab or similar as supplemental material.
</p>
<p>If you would like to study other data sets, feel free to propose other
sets. What we have proposed 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
https://archive.ics.uci.edu/ml/index.php is an excellent site to look
up for examples and inspiration. Kaggle.com is an equally interesting
site. Feel free to explore these sites.
</p>
<h2 id="classification-and-regression-writing-our-own-neural-network-code" class="anchor">Classification and Regression, writing our own neural network code </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. The exercises from week 41 and 42 (see <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html</tt></a> and <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html</tt></a>) as well as the lecture material from the same weeks (see <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html</tt></a> and <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html</tt></a>) should contain enough information for you to get started with writing your own code.
</p>
<p>We will also reuse our codes on gradient descent methods from project 1.</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> The simple one-dimensional function Runge function from project 1, that is \( f(x) = \frac{1}{1+25x^2} \). We recommend using a simpler function when developing your neural network code for regression problems. You should however feel free to discuss and study other functions, such as the the two-dimensional Runge function \( f(x,y)=\left[(10x - 5)^2 + (10y - 5)^2 + 1 \right]^{-1} \), or even more complicated two-dimensional functions (see the supplementary material of <a href="https://www.nature.com/articles/s41467-025-61362-4" target="_self"><tt>https://www.nature.com/articles/s41467-025-61362-4</tt></a> for an extensive list of two-dimensional functions).</li>
</ol>
<li> Classification.
<ol type="a"></li>
<li> We will consider the multiclass classification problem given by the full MNIST data set. The one included in <b>scikit-learn</b> is reduced data. The full data set is at <a href="https://www.kaggle.com/datasets/hojjatk/mnist-dataset" target="_self"><tt>https://www.kaggle.com/datasets/hojjatk/mnist-dataset</tt></a>.</li>
</ol>
</ul>
<p>We will start with a regression problem and we will reuse our codes on gradient descent methods from project 1.</p>
<h3 id="part-a-analytical-warm-up" class="anchor">Part a): Analytical warm-up </h3>
<p>When using our gradient machinery from project 1, we will need the expressions for the cost/loss functions and their respective
gradients. The functions whose gradients we need are:
</p>
<ol>
<li> The mean-squared error (MSE) with and without the \( L_1 \) and \( L_2 \) norms (regression problems)</li>
<li> The binary cross entropy (aka log loss) for classification problems with and without \( L_1 \) and \( L_2 \) norms</li>
<li> The multiclass cross entropy cost/loss function (aka Softmax cross entropy or just Softmax loss function)</li>
</ol>
<p>Set up these three cost/loss functions and their respective derivatives and explain the various terms.</p>
<p>We will test three activation functions for our neural network setup, these are the </p>
<ol>
<li> The Sigmoid (aka <b>logit</b>) function,</li>
<li> the RELU function and</li>
<li> the Leaky RELU function</li>
</ol>
<p>Set up their expressions and their first derivatives.
You may consult the lecture notes (with codes and more) from week 42 at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html</tt></a>.
</p>
<h3 id="reminder-about-the-gradient-machinery-from-project-1" class="anchor">Reminder about the gradient machinery from project 1 </h3>
<p>In the setup of a neural network code you will need your gradient descent codes from
project 1. For neural networks we will recommend using stochastic
gradient descent with either the RMSprop or the ADAM algorithms for
updating the learning rates. But you should feel free to try plain gradient descent as well.
</p>
<p>We recommend reading chapter 8 on optimization from the textbook of
Goodfellow, Bengio and Courville at
<a href="https://www.deeplearningbook.org/" target="_self"><tt>https://www.deeplearningbook.org/</tt></a>. This chapter contains many
useful insights and discussions on the optimization part of machine
learning. A useful reference on the back progagation algorithm is
Nielsen's book at <a href="http://neuralnetworksanddeeplearning.com/" target="_self"><tt>http://neuralnetworksanddeeplearning.com/</tt></a>.
</p>
<p>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 \) .
</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 FFNN code implementing the back
propagation algorithm discussed in the lecture slides from week 41 at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html</tt></a> and week 42 at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html</tt></a>.
</p>
<p>We will focus on a regression problem first, using the one-dimensional Runge function</p>
$$
f(x) = \frac{1}{1+25x^2},
$$
<p>from project 1.</p>
<p>Use only the mean-squared error as cost function (no regularization terms) and
write an FFNN code for a regression problem with a flexible number of hidden
layers and nodes using only 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?
And how would you set up your design/feature matrix? Hint: does it have to represent a polynomial approximation as you did in project 1?
</p>
<p>Train your network and compare the results with those from your OLS
regression code from project 1 using the one-dimensional Runge
function. When comparing your neural network code with the OLS
results from project 1, use the same data sets which gave you the best
MSE score. Moreover, use the polynomial order from project 1 that gave you the
best result. Compare these results with your neural network with one
and two hidden layers using \( 50 \) and \( 100 \) hidden nodes, respectively.
</p>
<p>Comment your results and give a critical discussion of the results
obtained with the OLS code from project 1 and your own neural network
code. Make an analysis of the learning rates employed to find the
optimal MSE and \( R2 \) scores. Test both stochastic gradient descent
with RMSprop and ADAM and plain gradient descent with different
learning rates.
</p>
<p>You should, as you did in project 1, scale your data.</p>
<h3 id="part-c-testing-against-other-software-libraries" class="anchor">Part c): Testing against other software libraries </h3>
<p>You should test your results against a similar code using <b>Scikit-Learn</b> (see the examples in the above lecture notes from weeks 41 and 42) or <b>tensorflow/keras</b> or <b>Pytorch</b> (for Pytorch, see Raschka et al.'s text chapters 12 and 13). </p>
<p>Furthermore, you should also test that your derivatives are correctly
calculated using automatic differentiation, using for example the
<b>Autograd</b> library or the <b>JAX</b> library. It is optional to implement
these libraries for the present project. In this project they serve as
useful tests of our derivatives.
</p>
<h3 id="part-d-testing-different-activation-functions-and-depths-of-the-neural-network" class="anchor">Part d): Testing different activation functions and depths of the neural network </h3>
<p>You should also test different activation functions for the hidden
layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and
discuss your results. Test your results as functions of the number of hidden layers and nodes. Do you see signs of overfitting?
It is optional in this project to perform a bias-variance trade-off analysis.
</p>
<h3 id="part-e-testing-different-norms" class="anchor">Part e): Testing different norms </h3>
<p>Finally, still using the one-dimensional Runge function, add now the
hyperparameters \( \lambda \) with the \( L_2 \) and \( L_1 \) norms. Find the
optimal results for the hyperparameters \( \lambda \) and the learning
rates \( \eta \) and neural network architecture and compare the \( L_2 \) results with Ridge regression from
project 1 and the \( L_1 \) results with the Lasso calculations of project 1.
Use again the same data sets and the best results from project 1 in your comparisons.
</p>
<h3 id="part-f-classification-analysis-using-neural-networks" class="anchor">Part f): 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), d) and e) in order to perform a classification
analysis. The classification problem we will study is the multiclass
MNIST problem, see the description of the full data set at
<a href="https://www.kaggle.com/datasets/hojjatk/mnist-dataset" target="_self"><tt>https://www.kaggle.com/datasets/hojjatk/mnist-dataset</tt></a>. We will use the Softmax cross entropy function discussed in a).
The MNIST data set discussed in the lecture notes from week 42 is a downscaled variant of the full dataset.
</p>
<p>Feel free to suggest other data sets. If you find the classic MNIST data set somewhat limited, feel free to try the
MNIST-Fashion data set at for example <a href="https://www.kaggle.com/datasets/zalando-research/fashionmnist" target="_self"><tt>https://www.kaggle.com/datasets/zalando-research/fashionmnist</tt></a>.
</p>
<p>To set up the data set, the following python programs may be useful</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">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> fetch_openml
<span style="color: #408080; font-style: italic"># Fetch the MNIST dataset</span>
mnist <span style="color: #666666">=</span> fetch_openml(<span style="color: #BA2121">&#39;mnist_784&#39;</span>, version<span style="color: #666666">=1</span>, as_frame<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>, parser<span style="color: #666666">=</span><span style="color: #BA2121">&#39;auto&#39;</span>)
<span style="color: #408080; font-style: italic"># Extract data (features) and target (labels)</span>
X <span style="color: #666666">=</span> mnist<span style="color: #666666">.</span>data
y <span style="color: #666666">=</span> mnist<span style="color: #666666">.</span>target
</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>You should consider scaling the data. The Pixel values in MNIST range from 0 to 255. Scaling them to a 0-1 range can improve the performance of some models. That is, you could implement the following scaling</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%;">X <span style="color: #666666">=</span> X <span style="color: #666666">/</span> <span style="color: #666666">255.0</span>
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>And then perform the standard train-test splitting</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">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>, random_state<span style="color: #666666">=42</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>To measure the performance of our classification problem we will 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 \), various activation functions, number of hidden layers and nodes and activation functions. </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>
<p>If you have time, you can use the functionality of <b>scikit-learn</b> and compare your neural network results with those from Logistic regression. This is optional.
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. Your neural network code can implement the equivalent of logistic regression by simply setting the number of hidden layers to zero.
</p>
<p>If you wish to compare with say Logisti Regression from <b>scikit-learn</b>, the following code uses the above data set</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">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
<span style="color: #408080; font-style: italic"># Initialize the model</span>
model <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">&#39;saga&#39;</span>, multi_class<span style="color: #666666">=</span><span style="color: #BA2121">&#39;multinomial&#39;</span>, max_iter<span style="color: #666666">=1000</span>, random_state<span style="color: #666666">=42</span>)
<span style="color: #408080; font-style: italic"># Train the model</span>
model<span style="color: #666666">.</span>fit(X_train, y_train)
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
<span style="color: #408080; font-style: italic"># Make predictions on the test set</span>
y_pred <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(X_test)
<span style="color: #408080; font-style: italic"># Calculate accuracy</span>
accuracy <span style="color: #666666">=</span> accuracy_score(y_test, y_pred)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Model Accuracy: </span><span style="color: #BB6688; font-weight: bold">{</span>accuracy<span style="color: #BB6688; font-weight: bold">:</span><span style="color: #BA2121">.4f</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<h3 id="part-g-critical-evaluation-of-the-various-algorithms" class="anchor">Part g) 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 Nielsen's book at <a href="http://neuralnetworksanddeeplearning.com/" target="_self"><tt>http://neuralnetworksanddeeplearning.com/</tt></a>. It is an excellent read.</li>
<li> Goodfellow, Bengio and Courville, Deep Learning at <a href="https://www.deeplearningbook.org/" target="_self"><tt>https://www.deeplearningbook.org/</tt></a>. Here we recommend chapters 6, 7 and 8</li>
<li> Raschka et al. at <a href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" target="_self"><tt>https://sebastianraschka.com/blog/2022/ml-pytorch-book.html</tt></a>. Here we recommend chapters 11, 12 and 13.</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 write a report for each
project.
</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.</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-2025, "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>
@@ -0,0 +1,608 @@
<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html Project2.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=Project2
-->
<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 10 (Midnight)">
<title>Project 2 on Machine Learning, deadline November 10 (Midnight)</title>
<style type="text/css">
/* bloodish style */
body {
font-family: Helvetica, Verdana, Arial, Sans-serif;
color: #404040;
background: #ffffff;
}
h1 { font-size: 1.8em; color: #8A0808; }
h2 { font-size: 1.6em; color: #8A0808; }
h3 { font-size: 1.4em; color: #8A0808; }
h4 { font-size: 1.2em; color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
p { text-indent: 0px; }
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-style: normal; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa; }div.highlight {
border: 1px solid #cfcfcf;
border-radius: 2px;
line-height: 1.21429em;
}
div.cell {
width: 100%;
padding: 5px 5px 5px 0;
margin: 0;
outline: none;
}
div.input {
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.inner_cell {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
box-flex: 1;
flex: 1;
}
div.input_area {
border: 1px solid #cfcfcf;
border-radius: 4px;
background: #f7f7f7;
line-height: 1.21429em;
}
div.input_area > div.highlight {
margin: .4em;
border: none;
padding: 0;
background-color: transparent;
}
div.output_wrapper {
position: relative;
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
.output {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
div.output_area {
padding: 0;
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.output_subarea {
padding: .4em .4em 0 .4em;
box-flex: 1;
flex: 1;
}
div.output_text {
text-align: left;
color: #000;
line-height: 1.21429em;
}
div { text-align: justify; text-justify: inter-word; }
.tab {
padding-left: 1.5em;
}
div.toc p,a {
line-height: 1.3;
margin-top: 1.1;
margin-bottom: 1.1;
}
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Deliverables', 2, None, 'deliverables'),
('Preamble: Note on writing reports, using reference material, '
'AI and other tools',
3,
None,
'preamble-note-on-writing-reports-using-reference-material-ai-and-other-tools'),
('Classification and Regression, writing our own neural network '
'code',
2,
None,
'classification-and-regression-writing-our-own-neural-network-code'),
('Part a): Analytical warm-up',
3,
None,
'part-a-analytical-warm-up'),
('Reminder about the gradient machinery from project 1',
3,
None,
'reminder-about-the-gradient-machinery-from-project-1'),
('Part b): Writing your own Neural Network code',
3,
None,
'part-b-writing-your-own-neural-network-code'),
('Part c): Testing against other software libraries',
3,
None,
'part-c-testing-against-other-software-libraries'),
('Part d): Testing different activation functions and depths of '
'the neural network',
3,
None,
'part-d-testing-different-activation-functions-and-depths-of-the-neural-network'),
('Part e): Testing different norms',
3,
None,
'part-e-testing-different-norms'),
('Part f): Classification analysis using neural networks',
3,
None,
'part-f-classification-analysis-using-neural-networks'),
('Part g) Critical evaluation of the various algorithms',
3,
None,
'part-g-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: "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 2 on Machine Learning, deadline November 10 (Midnight)</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>October 14, 2025</h4>
</center> <!-- date -->
<br>
<h2 id="deliverables">Deliverables </h2>
<p>First, join a group in canvas with your group partners. Pick an avaliable group for Project 2 in the <b>People</b> page.</p>
<p>In canvas, deliver as a group and include:</p>
<ul>
<li> A PDF of your report which follows the guidelines covered below and in the week 39 exercises. Additional requirements include:</li>
<ul>
<li> It should be around 5000 words, use the word counter in Overleaf for this. This often corresponds to 10-12 pages. References and appendices are excluded from the word count</li>
<li> It should include around 10-15 figures. You can include more figures in appendices and/or as supplemental material in your repository.</li>
</ul>
<li> A comment linking to your github repository (or folder in one of your github repositories) for this project. The repository must include</li>
</ul>
<p>A PDF file of the report</p>
<ul>
<li> A folder named Code, where you put python files for your functions and notebooks for reproducing your results. Remember to use a seed for generating random data and for train-test splits when generating final results.</li>
<li> A README file with the name of the group members</li>
<li> a short description of the project</li>
<li> a description of how to install the required packages to run your code from a requirements.txt file or similar (such as a plain text description) names and descriptions of the various notebooks in the Code folder and the results they produce</li>
</ul>
<h3 id="preamble-note-on-writing-reports-using-reference-material-ai-and-other-tools">Preamble: Note on writing reports, using reference material, AI and other tools </h3>
<p>We want you to answer the three different projects by handing in
reports written like a standard scientific/technical report. The links
at
https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects
contain more information. There you can find examples of previous
reports, the projects themselves, how we grade reports etc. How to
write reports will also be discussed during the various lab
sessions. Please do ask us if you are in doubt.
</p>
<p>When using codes and material from other sources, you should refer to
these in the bibliography of your report, indicating wherefrom you for
example got the code, whether this is from the lecture notes,
softwares like Scikit-Learn, TensorFlow, PyTorch or other
sources. These sources should always be cited correctly. How to cite
some of the libraries is often indicated from their corresponding
GitHub sites or websites, see for example how to cite Scikit-Learn at
https://scikit-learn.org/dev/about.html.
</p>
<p>We enocurage you to use tools like ChatGPT or similar in writing the
report. If you use for example ChatGPT, please do cite it properly and
include (if possible) your questions and answers as an addition to the
report. This can be uploaded to for example your website,
GitHub/GitLab or similar as supplemental material.
</p>
<p>If you would like to study other data sets, feel free to propose other
sets. What we have proposed 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
https://archive.ics.uci.edu/ml/index.php is an excellent site to look
up for examples and inspiration. Kaggle.com is an equally interesting
site. Feel free to explore these sites.
</p>
<h2 id="classification-and-regression-writing-our-own-neural-network-code">Classification and Regression, writing our own neural network code </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. The exercises from week 41 and 42 (see <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html" target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html</tt></a> and <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html" target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html</tt></a>) as well as the lecture material from the same weeks (see <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html" target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html</tt></a> and <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html</tt></a>) should contain enough information for you to get started with writing your own code.
</p>
<p>We will also reuse our codes on gradient descent methods from project 1.</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> The simple one-dimensional function Runge function from project 1, that is \( f(x) = \frac{1}{1+25x^2} \). We recommend using a simpler function when developing your neural network code for regression problems. You should however feel free to discuss and study other functions, such as the the two-dimensional Runge function \( f(x,y)=\left[(10x - 5)^2 + (10y - 5)^2 + 1 \right]^{-1} \), or even more complicated two-dimensional functions (see the supplementary material of <a href="https://www.nature.com/articles/s41467-025-61362-4" target="_blank"><tt>https://www.nature.com/articles/s41467-025-61362-4</tt></a> for an extensive list of two-dimensional functions).</li>
</ol>
<li> Classification.
<ol type="a"></li>
<li> We will consider the multiclass classification problem given by the full MNIST data set. The one included in <b>scikit-learn</b> is reduced data. The full data set is at <a href="https://www.kaggle.com/datasets/hojjatk/mnist-dataset" target="_blank"><tt>https://www.kaggle.com/datasets/hojjatk/mnist-dataset</tt></a>.</li>
</ol>
</ul>
<p>We will start with a regression problem and we will reuse our codes on gradient descent methods from project 1.</p>
<h3 id="part-a-analytical-warm-up">Part a): Analytical warm-up </h3>
<p>When using our gradient machinery from project 1, we will need the expressions for the cost/loss functions and their respective
gradients. The functions whose gradients we need are:
</p>
<ol>
<li> The mean-squared error (MSE) with and without the \( L_1 \) and \( L_2 \) norms (regression problems)</li>
<li> The binary cross entropy (aka log loss) for classification problems with and without \( L_1 \) and \( L_2 \) norms</li>
<li> The multiclass cross entropy cost/loss function (aka Softmax cross entropy or just Softmax loss function)</li>
</ol>
<p>Set up these three cost/loss functions and their respective derivatives and explain the various terms.</p>
<p>We will test three activation functions for our neural network setup, these are the </p>
<ol>
<li> The Sigmoid (aka <b>logit</b>) function,</li>
<li> the RELU function and</li>
<li> the Leaky RELU function</li>
</ol>
<p>Set up their expressions and their first derivatives.
You may consult the lecture notes (with codes and more) from week 42 at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html</tt></a>.
</p>
<h3 id="reminder-about-the-gradient-machinery-from-project-1">Reminder about the gradient machinery from project 1 </h3>
<p>In the setup of a neural network code you will need your gradient descent codes from
project 1. For neural networks we will recommend using stochastic
gradient descent with either the RMSprop or the ADAM algorithms for
updating the learning rates. But you should feel free to try plain gradient descent as well.
</p>
<p>We recommend reading chapter 8 on optimization from the textbook of
Goodfellow, Bengio and Courville at
<a href="https://www.deeplearningbook.org/" target="_blank"><tt>https://www.deeplearningbook.org/</tt></a>. This chapter contains many
useful insights and discussions on the optimization part of machine
learning. A useful reference on the back progagation algorithm is
Nielsen's book at <a href="http://neuralnetworksanddeeplearning.com/" target="_blank"><tt>http://neuralnetworksanddeeplearning.com/</tt></a>.
</p>
<p>You will find the Python <a href="https://seaborn.pydata.org/generated/seaborn.heatmap.html" target="_blank">Seaborn
package</a>
useful when plotting the results as function of the learning rate
\( \eta \) and the hyper-parameter \( \lambda \) .
</p>
<h3 id="part-b-writing-your-own-neural-network-code">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 FFNN code implementing the back
propagation algorithm discussed in the lecture slides from week 41 at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html" target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html</tt></a> and week 42 at <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html</tt></a>.
</p>
<p>We will focus on a regression problem first, using the one-dimensional Runge function</p>
$$
f(x) = \frac{1}{1+25x^2},
$$
<p>from project 1.</p>
<p>Use only the mean-squared error as cost function (no regularization terms) and
write an FFNN code for a regression problem with a flexible number of hidden
layers and nodes using only 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?
And how would you set up your design/feature matrix? Hint: does it have to represent a polynomial approximation as you did in project 1?
</p>
<p>Train your network and compare the results with those from your OLS
regression code from project 1 using the one-dimensional Runge
function. When comparing your neural network code with the OLS
results from project 1, use the same data sets which gave you the best
MSE score. Moreover, use the polynomial order from project 1 that gave you the
best result. Compare these results with your neural network with one
and two hidden layers using \( 50 \) and \( 100 \) hidden nodes, respectively.
</p>
<p>Comment your results and give a critical discussion of the results
obtained with the OLS code from project 1 and your own neural network
code. Make an analysis of the learning rates employed to find the
optimal MSE and \( R2 \) scores. Test both stochastic gradient descent
with RMSprop and ADAM and plain gradient descent with different
learning rates.
</p>
<p>You should, as you did in project 1, scale your data.</p>
<h3 id="part-c-testing-against-other-software-libraries">Part c): Testing against other software libraries </h3>
<p>You should test your results against a similar code using <b>Scikit-Learn</b> (see the examples in the above lecture notes from weeks 41 and 42) or <b>tensorflow/keras</b> or <b>Pytorch</b> (for Pytorch, see Raschka et al.'s text chapters 12 and 13). </p>
<p>Furthermore, you should also test that your derivatives are correctly
calculated using automatic differentiation, using for example the
<b>Autograd</b> library or the <b>JAX</b> library. It is optional to implement
these libraries for the present project. In this project they serve as
useful tests of our derivatives.
</p>
<h3 id="part-d-testing-different-activation-functions-and-depths-of-the-neural-network">Part d): Testing different activation functions and depths of the neural network </h3>
<p>You should also test different activation functions for the hidden
layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and
discuss your results. Test your results as functions of the number of hidden layers and nodes. Do you see signs of overfitting?
It is optional in this project to perform a bias-variance trade-off analysis.
</p>
<h3 id="part-e-testing-different-norms">Part e): Testing different norms </h3>
<p>Finally, still using the one-dimensional Runge function, add now the
hyperparameters \( \lambda \) with the \( L_2 \) and \( L_1 \) norms. Find the
optimal results for the hyperparameters \( \lambda \) and the learning
rates \( \eta \) and neural network architecture and compare the \( L_2 \) results with Ridge regression from
project 1 and the \( L_1 \) results with the Lasso calculations of project 1.
Use again the same data sets and the best results from project 1 in your comparisons.
</p>
<h3 id="part-f-classification-analysis-using-neural-networks">Part f): 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), d) and e) in order to perform a classification
analysis. The classification problem we will study is the multiclass
MNIST problem, see the description of the full data set at
<a href="https://www.kaggle.com/datasets/hojjatk/mnist-dataset" target="_blank"><tt>https://www.kaggle.com/datasets/hojjatk/mnist-dataset</tt></a>. We will use the Softmax cross entropy function discussed in a).
The MNIST data set discussed in the lecture notes from week 42 is a downscaled variant of the full dataset.
</p>
<p>Feel free to suggest other data sets. If you find the classic MNIST data set somewhat limited, feel free to try the
MNIST-Fashion data set at for example <a href="https://www.kaggle.com/datasets/zalando-research/fashionmnist" target="_blank"><tt>https://www.kaggle.com/datasets/zalando-research/fashionmnist</tt></a>.
</p>
<p>To set up the data set, the following python programs may be useful</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">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> fetch_openml
<span style="color: #408080; font-style: italic"># Fetch the MNIST dataset</span>
mnist <span style="color: #666666">=</span> fetch_openml(<span style="color: #BA2121">&#39;mnist_784&#39;</span>, version<span style="color: #666666">=1</span>, as_frame<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>, parser<span style="color: #666666">=</span><span style="color: #BA2121">&#39;auto&#39;</span>)
<span style="color: #408080; font-style: italic"># Extract data (features) and target (labels)</span>
X <span style="color: #666666">=</span> mnist<span style="color: #666666">.</span>data
y <span style="color: #666666">=</span> mnist<span style="color: #666666">.</span>target
</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>You should consider scaling the data. The Pixel values in MNIST range from 0 to 255. Scaling them to a 0-1 range can improve the performance of some models. That is, you could implement the following scaling</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%;">X <span style="color: #666666">=</span> X <span style="color: #666666">/</span> <span style="color: #666666">255.0</span>
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>And then perform the standard train-test splitting</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">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>, random_state<span style="color: #666666">=42</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>To measure the performance of our classification problem we will 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 \), various activation functions, number of hidden layers and nodes and activation functions. </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>
<p>If you have time, you can use the functionality of <b>scikit-learn</b> and compare your neural network results with those from Logistic regression. This is optional.
The weblink here <a href="https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3" target="_blank"><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. Your neural network code can implement the equivalent of logistic regression by simply setting the number of hidden layers to zero.
</p>
<p>If you wish to compare with say Logisti Regression from <b>scikit-learn</b>, the following code uses the above data set</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">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
<span style="color: #408080; font-style: italic"># Initialize the model</span>
model <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">&#39;saga&#39;</span>, multi_class<span style="color: #666666">=</span><span style="color: #BA2121">&#39;multinomial&#39;</span>, max_iter<span style="color: #666666">=1000</span>, random_state<span style="color: #666666">=42</span>)
<span style="color: #408080; font-style: italic"># Train the model</span>
model<span style="color: #666666">.</span>fit(X_train, y_train)
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
<span style="color: #408080; font-style: italic"># Make predictions on the test set</span>
y_pred <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(X_test)
<span style="color: #408080; font-style: italic"># Calculate accuracy</span>
accuracy <span style="color: #666666">=</span> accuracy_score(y_test, y_pred)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Model Accuracy: </span><span style="color: #BB6688; font-weight: bold">{</span>accuracy<span style="color: #BB6688; font-weight: bold">:</span><span style="color: #BA2121">.4f</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<h3 id="part-g-critical-evaluation-of-the-various-algorithms">Part g) 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">Background literature </h2>
<ol>
<li> The text of Michael Nielsen is highly recommended, see Nielsen's book at <a href="http://neuralnetworksanddeeplearning.com/" target="_blank"><tt>http://neuralnetworksanddeeplearning.com/</tt></a>. It is an excellent read.</li>
<li> Goodfellow, Bengio and Courville, Deep Learning at <a href="https://www.deeplearningbook.org/" target="_blank"><tt>https://www.deeplearningbook.org/</tt></a>. Here we recommend chapters 6, 7 and 8</li>
<li> Raschka et al. at <a href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" target="_blank"><tt>https://sebastianraschka.com/blog/2022/ml-pytorch-book.html</tt></a>. Here we recommend chapters 11, 12 and 13.</li>
</ol>
<h2 id="introduction-to-numerical-projects">Introduction to numerical projects </h2>
<p>Here follows a brief recipe and recommendation on how to write a report for each
project.
</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.</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 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="_blank"><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>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2025, "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>
@@ -0,0 +1,554 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "3fa6e27c",
"metadata": {
"editable": true
},
"source": [
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
"doconce format html Project2.do.txt -->\n",
"<!-- dom:TITLE: Project 2 on Machine Learning, deadline November 10 (Midnight) -->"
]
},
{
"cell_type": "markdown",
"id": "a03c6301",
"metadata": {
"editable": true
},
"source": [
"# Project 2 on Machine Learning, deadline November 10 (Midnight)\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: **October 14, 2025**"
]
},
{
"cell_type": "markdown",
"id": "cb555c06",
"metadata": {
"editable": true
},
"source": [
"## Deliverables\n",
"\n",
"First, join a group in canvas with your group partners. Pick an avaliable group for Project 2 in the **People** page.\n",
"\n",
"In canvas, deliver as a group and include:\n",
"\n",
"* A PDF of your report which follows the guidelines covered below and in the week 39 exercises. Additional requirements include:\n",
"\n",
" * It should be around 5000 words, use the word counter in Overleaf for this. This often corresponds to 10-12 pages. References and appendices are excluded from the word count\n",
"\n",
" * It should include around 10-15 figures. You can include more figures in appendices and/or as supplemental material in your repository.\n",
"\n",
"* A comment linking to your github repository (or folder in one of your github repositories) for this project. The repository must include\n",
"\n",
"A PDF file of the report\n",
" * A folder named Code, where you put python files for your functions and notebooks for reproducing your results. Remember to use a seed for generating random data and for train-test splits when generating final results.\n",
"\n",
" * A README file with the name of the group members\n",
"\n",
" * a short description of the project\n",
"\n",
" * a description of how to install the required packages to run your code from a requirements.txt file or similar (such as a plain text description) names and descriptions of the various notebooks in the Code folder and the results they produce"
]
},
{
"cell_type": "markdown",
"id": "a1606b1d",
"metadata": {
"editable": true
},
"source": [
"### Preamble: Note on writing reports, using reference material, AI and other tools\n",
"\n",
"We want you to answer the three different projects by handing in\n",
"reports written like a standard scientific/technical report. The links\n",
"at\n",
"https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects\n",
"contain more information. There you can find examples of previous\n",
"reports, the projects themselves, how we grade reports etc. How to\n",
"write reports will also be discussed during the various lab\n",
"sessions. Please do ask us if you are in doubt.\n",
"\n",
"When using codes and material from other sources, you should refer to\n",
"these in the bibliography of your report, indicating wherefrom you for\n",
"example got the code, whether this is from the lecture notes,\n",
"softwares like Scikit-Learn, TensorFlow, PyTorch or other\n",
"sources. These sources should always be cited correctly. How to cite\n",
"some of the libraries is often indicated from their corresponding\n",
"GitHub sites or websites, see for example how to cite Scikit-Learn at\n",
"https://scikit-learn.org/dev/about.html.\n",
"\n",
"We enocurage you to use tools like ChatGPT or similar in writing the\n",
"report. If you use for example ChatGPT, please do cite it properly and\n",
"include (if possible) your questions and answers as an addition to the\n",
"report. This can be uploaded to for example your website,\n",
"GitHub/GitLab or similar as supplemental material.\n",
"\n",
"If you would like to study other data sets, feel free to propose other\n",
"sets. What we have proposed here are mere suggestions from our\n",
"side. If you opt for another data set, consider using a set which has\n",
"been studied in the scientific literature. This makes it easier for\n",
"you to compare and analyze your results. Comparing with existing\n",
"results from the scientific literature is also an essential element of\n",
"the scientific discussion. The University of California at Irvine with\n",
"its Machine Learning repository at\n",
"https://archive.ics.uci.edu/ml/index.php is an excellent site to look\n",
"up for examples and inspiration. Kaggle.com is an equally interesting\n",
"site. Feel free to explore these sites."
]
},
{
"cell_type": "markdown",
"id": "6cb2d855",
"metadata": {
"editable": true
},
"source": [
"## Classification and Regression, writing our own neural network code\n",
"\n",
"The main aim of this project is to study both classification and\n",
"regression problems by developing our own \n",
"feed-forward neural network (FFNN) code. The exercises from week 41 and 42 (see <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html> and <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html>) as well as the lecture material from the same weeks (see <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html> and <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html>) should contain enough information for you to get started with writing your own code.\n",
"\n",
"We will also reuse our codes on gradient descent methods from project 1.\n",
"\n",
"The data sets that we propose here are (the default sets)\n",
"\n",
"* 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\n",
"\n",
"a. The simple one-dimensional function Runge function from project 1, that is $f(x) = \\frac{1}{1+25x^2}$. We recommend using a simpler function when developing your neural network code for regression problems. You should however feel free to discuss and study other functions, such as the the two-dimensional Runge function $f(x,y)=\\left[(10x - 5)^2 + (10y - 5)^2 + 1 \\right]^{-1}$, or even more complicated two-dimensional functions (see the supplementary material of <https://www.nature.com/articles/s41467-025-61362-4> for an extensive list of two-dimensional functions). \n",
"\n",
"* Classification.\n",
"\n",
"a. We will consider the multiclass classification problem given by the full MNIST data set. The one included in **scikit-learn** is reduced data. The full data set is at <https://www.kaggle.com/datasets/hojjatk/mnist-dataset>. \n",
"\n",
"We will start with a regression problem and we will reuse our codes on gradient descent methods from project 1."
]
},
{
"cell_type": "markdown",
"id": "6eb7d47f",
"metadata": {
"editable": true
},
"source": [
"### Part a): Analytical warm-up\n",
"\n",
"When using our gradient machinery from project 1, we will need the expressions for the cost/loss functions and their respective\n",
"gradients. The functions whose gradients we need are:\n",
"1. The mean-squared error (MSE) with and without the $L_1$ and $L_2$ norms (regression problems)\n",
"\n",
"2. The binary cross entropy (aka log loss) for classification problems with and without $L_1$ and $L_2$ norms\n",
"\n",
"3. The multiclass cross entropy cost/loss function (aka Softmax cross entropy or just Softmax loss function)\n",
"\n",
"Set up these three cost/loss functions and their respective derivatives and explain the various terms.\n",
"\n",
"We will test three activation functions for our neural network setup, these are the \n",
"1. The Sigmoid (aka **logit**) function,\n",
"\n",
"2. the RELU function and\n",
"\n",
"3. the Leaky RELU function\n",
"\n",
"Set up their expressions and their first derivatives.\n",
"You may consult the lecture notes (with codes and more) from week 42 at <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html>."
]
},
{
"cell_type": "markdown",
"id": "2d071fd6",
"metadata": {
"editable": true
},
"source": [
"### Reminder about the gradient machinery from project 1\n",
"\n",
"In the setup of a neural network code you will need your gradient descent codes from\n",
"project 1. For neural networks we will recommend using stochastic\n",
"gradient descent with either the RMSprop or the ADAM algorithms for\n",
"updating the learning rates. But you should feel free to try plain gradient descent as well.\n",
"\n",
"We recommend reading chapter 8 on optimization from the textbook of\n",
"Goodfellow, Bengio and Courville at\n",
"<https://www.deeplearningbook.org/>. This chapter contains many\n",
"useful insights and discussions on the optimization part of machine\n",
"learning. A useful reference on the back progagation algorithm is\n",
"Nielsen's book at <http://neuralnetworksanddeeplearning.com/>. \n",
"\n",
"You will find the Python [Seaborn\n",
"package](https://seaborn.pydata.org/generated/seaborn.heatmap.html)\n",
"useful when plotting the results as function of the learning rate\n",
"$\\eta$ and the hyper-parameter $\\lambda$ ."
]
},
{
"cell_type": "markdown",
"id": "79aab198",
"metadata": {
"editable": true
},
"source": [
"### Part b): Writing your own Neural Network code\n",
"\n",
"Your aim now, and this is the central part of this project, is to\n",
"write your own FFNN code implementing the back\n",
"propagation algorithm discussed in the lecture slides from week 41 at <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html> and week 42 at <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html>.\n",
"\n",
"We will focus on a regression problem first, using the one-dimensional Runge function"
]
},
{
"cell_type": "markdown",
"id": "ce89599d",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"f(x) = \\frac{1}{1+25x^2},\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "0f5c6fd3",
"metadata": {
"editable": true
},
"source": [
"from project 1.\n",
"\n",
"Use only the mean-squared error as cost function (no regularization terms) and \n",
"write an FFNN code for a regression problem with a flexible number of hidden\n",
"layers and nodes using only the Sigmoid function as activation function for\n",
"the hidden layers. Initialize the weights using a normal\n",
"distribution. How would you initialize the biases? And which\n",
"activation function would you select for the final output layer?\n",
"And how would you set up your design/feature matrix? Hint: does it have to represent a polynomial approximation as you did in project 1? \n",
"\n",
"Train your network and compare the results with those from your OLS\n",
"regression code from project 1 using the one-dimensional Runge\n",
"function. When comparing your neural network code with the OLS\n",
"results from project 1, use the same data sets which gave you the best\n",
"MSE score. Moreover, use the polynomial order from project 1 that gave you the\n",
"best result. Compare these results with your neural network with one\n",
"and two hidden layers using $50$ and $100$ hidden nodes, respectively.\n",
"\n",
"Comment your results and give a critical discussion of the results\n",
"obtained with the OLS code from project 1 and your own neural network\n",
"code. Make an analysis of the learning rates employed to find the\n",
"optimal MSE and $R2$ scores. Test both stochastic gradient descent\n",
"with RMSprop and ADAM and plain gradient descent with different\n",
"learning rates.\n",
"\n",
"You should, as you did in project 1, scale your data."
]
},
{
"cell_type": "markdown",
"id": "a1ee77ac",
"metadata": {
"editable": true
},
"source": [
"### Part c): Testing against other software libraries\n",
"\n",
"You should test your results against a similar code using **Scikit-Learn** (see the examples in the above lecture notes from weeks 41 and 42) or **tensorflow/keras** or **Pytorch** (for Pytorch, see Raschka et al.'s text chapters 12 and 13). \n",
"\n",
"Furthermore, you should also test that your derivatives are correctly\n",
"calculated using automatic differentiation, using for example the\n",
"**Autograd** library or the **JAX** library. It is optional to implement\n",
"these libraries for the present project. In this project they serve as\n",
"useful tests of our derivatives."
]
},
{
"cell_type": "markdown",
"id": "cbbb5ef7",
"metadata": {
"editable": true
},
"source": [
"### Part d): Testing different activation functions and depths of the neural network\n",
"\n",
"You should also test different activation functions for the hidden\n",
"layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and\n",
"discuss your results. Test your results as functions of the number of hidden layers and nodes. Do you see signs of overfitting?\n",
"It is optional in this project to perform a bias-variance trade-off analysis."
]
},
{
"cell_type": "markdown",
"id": "ec569b37",
"metadata": {
"editable": true
},
"source": [
"### Part e): Testing different norms\n",
"\n",
"Finally, still using the one-dimensional Runge function, add now the\n",
"hyperparameters $\\lambda$ with the $L_2$ and $L_1$ norms. Find the\n",
"optimal results for the hyperparameters $\\lambda$ and the learning\n",
"rates $\\eta$ and neural network architecture and compare the $L_2$ results with Ridge regression from\n",
"project 1 and the $L_1$ results with the Lasso calculations of project 1.\n",
"Use again the same data sets and the best results from project 1 in your comparisons."
]
},
{
"cell_type": "markdown",
"id": "24327556",
"metadata": {
"editable": true
},
"source": [
"### Part f): Classification analysis using neural networks\n",
"\n",
"With a well-written code it should now be easy to change the\n",
"activation function for the output layer.\n",
"\n",
"Here we will change the cost function for our neural network code\n",
"developed in parts b), d) and e) in order to perform a classification\n",
"analysis. The classification problem we will study is the multiclass\n",
"MNIST problem, see the description of the full data set at\n",
"<https://www.kaggle.com/datasets/hojjatk/mnist-dataset>. We will use the Softmax cross entropy function discussed in a). \n",
"The MNIST data set discussed in the lecture notes from week 42 is a downscaled variant of the full dataset. \n",
"\n",
"Feel free to suggest other data sets. If you find the classic MNIST data set somewhat limited, feel free to try the \n",
"MNIST-Fashion data set at for example <https://www.kaggle.com/datasets/zalando-research/fashionmnist>.\n",
"\n",
"To set up the data set, the following python programs may be useful"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "7fa0dca1",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.datasets import fetch_openml\n",
"\n",
"# Fetch the MNIST dataset\n",
"mnist = fetch_openml('mnist_784', version=1, as_frame=False, parser='auto')\n",
"\n",
"# Extract data (features) and target (labels)\n",
"X = mnist.data\n",
"y = mnist.target"
]
},
{
"cell_type": "markdown",
"id": "f625eccf",
"metadata": {
"editable": true
},
"source": [
"You should consider scaling the data. The Pixel values in MNIST range from 0 to 255. Scaling them to a 0-1 range can improve the performance of some models. That is, you could implement the following scaling"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7614316d",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"X = X / 255.0"
]
},
{
"cell_type": "markdown",
"id": "9ebeee4a",
"metadata": {
"editable": true
},
"source": [
"And then perform the standard train-test splitting"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "2ec6b15a",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
]
},
{
"cell_type": "markdown",
"id": "7cad9a97",
"metadata": {
"editable": true
},
"source": [
"To measure the performance of our classification problem we will use the\n",
"so-called *accuracy* score. The accuracy is as you would expect just\n",
"the number of correctly guessed targets $t_i$ divided by the total\n",
"number of targets, that is"
]
},
{
"cell_type": "markdown",
"id": "2981093c",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\text{Accuracy} = \\frac{\\sum_{i=1}^n I(t_i = y_i)}{n} ,\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "7dee297d",
"metadata": {
"editable": true
},
"source": [
"where $I$ is the indicator function, $1$ if $t_i = y_i$ and $0$\n",
"otherwise if we have a binary classification problem. Here $t_i$\n",
"represents the target and $y_i$ the outputs of your FFNN code and $n$ is simply the number of targets $t_i$.\n",
"\n",
"Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter $\\lambda$, various activation functions, number of hidden layers and nodes and activation functions. \n",
"\n",
"Again, we strongly recommend that you compare your own neural Network\n",
"code for classification and pertinent results against a similar code using **Scikit-Learn** or **tensorflow/keras** or **pytorch**.\n",
"\n",
"If you have time, you can use the functionality of **scikit-learn** and compare your neural network results with those from Logistic regression. This is optional.\n",
"The weblink here <https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3>compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article. Your neural network code can implement the equivalent of logistic regression by simply setting the number of hidden layers to zero. \n",
"\n",
"If you wish to compare with say Logisti Regression from **scikit-learn**, the following code uses the above data set"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "ad088d25",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.linear_model import LogisticRegression\n",
"# Initialize the model\n",
"model = LogisticRegression(solver='saga', multi_class='multinomial', max_iter=1000, random_state=42)\n",
"# Train the model\n",
"model.fit(X_train, y_train)\n",
"from sklearn.metrics import accuracy_score\n",
"# Make predictions on the test set\n",
"y_pred = model.predict(X_test)\n",
"# Calculate accuracy\n",
"accuracy = accuracy_score(y_test, y_pred)\n",
"print(f\"Model Accuracy: {accuracy:.4f}\")"
]
},
{
"cell_type": "markdown",
"id": "e0ded2d6",
"metadata": {
"editable": true
},
"source": [
"### Part g) Critical evaluation of the various algorithms\n",
"\n",
"After all these glorious calculations, you should now summarize the\n",
"various algorithms and come with a critical evaluation of their pros\n",
"and cons. Which algorithm works best for the regression case and which\n",
"is best for the classification case. These codes can also be part of\n",
"your final project 3, but now applied to other data sets."
]
},
{
"cell_type": "markdown",
"id": "dc5dc11b",
"metadata": {
"editable": true
},
"source": [
"## Background literature\n",
"\n",
"1. The text of Michael Nielsen is highly recommended, see Nielsen's book at <http://neuralnetworksanddeeplearning.com/>. It is an excellent read.\n",
"\n",
"2. Goodfellow, Bengio and Courville, Deep Learning at <https://www.deeplearningbook.org/>. Here we recommend chapters 6, 7 and 8\n",
"\n",
"3. Raschka et al. at <https://sebastianraschka.com/blog/2022/ml-pytorch-book.html>. Here we recommend chapters 11, 12 and 13."
]
},
{
"cell_type": "markdown",
"id": "c6aeb5ed",
"metadata": {
"editable": true
},
"source": [
"## Introduction to numerical projects\n",
"\n",
"Here follows a brief recipe and recommendation on how to write a report for each\n",
"project.\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.\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": "a2da10ef",
"metadata": {
"editable": true
},
"source": [
"## Format for electronic delivery of report and programs\n",
"\n",
"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:\n",
"\n",
" * Use Canvas to hand in your projects, log in at <https://www.uio.no/english/services/it/education/canvas/> with your normal UiO username and password.\n",
"\n",
" * Upload **only** 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.\n",
"\n",
" * 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.\n",
"\n",
"Finally, \n",
"we encourage you to collaborate. Optimal working groups consist of \n",
"2-3 students. You can then hand in a common report."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,542 @@
%%
%% Automatically generated file from DocOnce source
%% (https://github.com/doconce/doconce/)
%% doconce format latex Project2.do.txt --print_latex_style=trac --latex_admon=paragraph
%%
% #ifdef PTEX2TEX_EXPLANATION
%%
%% The file follows the ptex2tex extended LaTeX format, see
%% ptex2tex: https://code.google.com/p/ptex2tex/
%%
%% Run
%% ptex2tex myfile
%% or
%% doconce ptex2tex myfile
%%
%% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex.
%% (The ptex2tex program: https://code.google.com/p/ptex2tex)
%% Many preprocess options can be added to ptex2tex or doconce ptex2tex
%%
%% ptex2tex -DMINTED myfile
%% doconce ptex2tex myfile envir=minted
%%
%% ptex2tex will typeset code environments according to a global or local
%% .ptex2tex.cfg configure file. doconce ptex2tex will typeset code
%% according to options on the command line (just type doconce ptex2tex to
%% see examples). If doconce ptex2tex has envir=minted, it enables the
%% minted style without needing -DMINTED.
% #endif
% #define PREAMBLE
% #ifdef PREAMBLE
%-------------------- begin preamble ----------------------
\documentclass[%
oneside, % oneside: electronic viewing, twoside: printing
final, % draft: marks overfull hboxes, figures with paths
10pt]{article}
\listfiles % print all files needed to compile this document
\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb}
\usepackage[table]{xcolor}
\usepackage{bm,ltablex,microtype}
\usepackage[pdftex]{graphicx}
\usepackage{ptex2tex}
% #ifdef MINTED
\usepackage{minted}
\usemintedstyle{default}
% #endif
\usepackage[T1]{fontenc}
%\usepackage[latin1]{inputenc}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern
% Hyperlinks in PDF:
\definecolor{linkcolor}{rgb}{0,0,0.4}
\usepackage{hyperref}
\hypersetup{
breaklinks=true,
colorlinks=true,
linkcolor=linkcolor,
urlcolor=linkcolor,
citecolor=black,
filecolor=black,
%filecolor=blue,
pdfmenubar=true,
pdftoolbar=true,
bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC
}
%\hyperbaseurl{} % hyperlinks are relative to this root
\setcounter{tocdepth}{2} % levels in table of contents
% --- fancyhdr package for fancy headers ---
\usepackage{fancyhdr}
\fancyhf{} % sets both header and footer to nothing
\renewcommand{\headrulewidth}{0pt}
\fancyfoot[LE,RO]{\thepage}
% Ensure copyright on titlepage (article style) and chapter pages (book style)
\fancypagestyle{plain}{
\fancyhf{}
\fancyfoot[C]{{\footnotesize \copyright\ 1999-2025, "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}}
% \renewcommand{\footrulewidth}{0mm}
\renewcommand{\headrulewidth}{0mm}
}
% Ensure copyright on titlepages with \thispagestyle{empty}
\fancypagestyle{empty}{
\fancyhf{}
\fancyfoot[C]{{\footnotesize \copyright\ 1999-2025, "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}}
\renewcommand{\footrulewidth}{0mm}
\renewcommand{\headrulewidth}{0mm}
}
\pagestyle{fancy}
% prevent orhpans and widows
\clubpenalty = 10000
\widowpenalty = 10000
% --- end of standard preamble for documents ---
% insert custom LaTeX commands...
\raggedbottom
\makeindex
\usepackage[totoc]{idxlayout} % for index in the toc
\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc
%-------------------- end preamble ----------------------
\begin{document}
% matching end for #ifdef PREAMBLE
% #endif
\newcommand{\exercisesection}[1]{\subsection*{#1}}
% ------------------- main content ----------------------
% ----------------- title -------------------------
\thispagestyle{empty}
\begin{center}
{\LARGE\bf
\begin{spacing}{1.25}
Project 2 on Machine Learning, deadline November 10 (Midnight)
\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}
October 14, 2025
\end{center}
% --- end date ---
\vspace{1cm}
\subsection{Deliverables}
First, join a group in canvas with your group partners. Pick an avaliable group for Project 2 in the \textbf{People} page.
In canvas, deliver as a group and include:
\begin{itemize}
\item A PDF of your report which follows the guidelines covered below and in the week 39 exercises. Additional requirements include:
\begin{itemize}
\item It should be around 5000 words, use the word counter in Overleaf for this. This often corresponds to 10-12 pages. References and appendices are excluded from the word count
\item It should include around 10-15 figures. You can include more figures in appendices and/or as supplemental material in your repository.
\end{itemize}
\noindent
\item A comment linking to your github repository (or folder in one of your github repositories) for this project. The repository must include
\end{itemize}
\noindent
A PDF file of the report
\begin{itemize}
\item A folder named Code, where you put python files for your functions and notebooks for reproducing your results. Remember to use a seed for generating random data and for train-test splits when generating final results.
\item A README file with the name of the group members
\item a short description of the project
\item a description of how to install the required packages to run your code from a requirements.txt file or similar (such as a plain text description) names and descriptions of the various notebooks in the Code folder and the results they produce
\end{itemize}
\noindent
\paragraph{Preamble: Note on writing reports, using reference material, AI and other tools.}
We want you to answer the three different projects by handing in
reports written like a standard scientific/technical report. The links
at
https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects
contain more information. There you can find examples of previous
reports, the projects themselves, how we grade reports etc. How to
write reports will also be discussed during the various lab
sessions. Please do ask us if you are in doubt.
When using codes and material from other sources, you should refer to
these in the bibliography of your report, indicating wherefrom you for
example got the code, whether this is from the lecture notes,
softwares like Scikit-Learn, TensorFlow, PyTorch or other
sources. These sources should always be cited correctly. How to cite
some of the libraries is often indicated from their corresponding
GitHub sites or websites, see for example how to cite Scikit-Learn at
https://scikit-learn.org/dev/about.html.
We enocurage you to use tools like ChatGPT or similar in writing the
report. If you use for example ChatGPT, please do cite it properly and
include (if possible) your questions and answers as an addition to the
report. This can be uploaded to for example your website,
GitHub/GitLab or similar as supplemental material.
If you would like to study other data sets, feel free to propose other
sets. What we have proposed 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
https://archive.ics.uci.edu/ml/index.php is an excellent site to look
up for examples and inspiration. Kaggle.com is an equally interesting
site. Feel free to explore these sites.
\subsection{Classification and Regression, writing our own neural network code}
The main aim of this project is to study both classification and
regression problems by developing our own
feed-forward neural network (FFNN) code. The exercises from week 41 and 42 (see \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html}} and \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html}}) as well as the lecture material from the same weeks (see \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html}} and \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}) should contain enough information for you to get started with writing your own code.
We will also reuse our codes on gradient descent methods from project 1.
The data sets that we propose here are (the default sets)
\begin{itemize}
\item 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
\begin{enumerate}
\item The simple one-dimensional function Runge function from project 1, that is $f(x) = \frac{1}{1+25x^2}$. We recommend using a simpler function when developing your neural network code for regression problems. You should however feel free to discuss and study other functions, such as the the two-dimensional Runge function $f(x,y)=\left[(10x - 5)^2 + (10y - 5)^2 + 1 \right]^{-1}$, or even more complicated two-dimensional functions (see the supplementary material of \href{{https://www.nature.com/articles/s41467-025-61362-4}}{\nolinkurl{https://www.nature.com/articles/s41467-025-61362-4}} for an extensive list of two-dimensional functions).
\end{enumerate}
\noindent
\item Classification.
\begin{enumerate}
\item We will consider the multiclass classification problem given by the full MNIST data set. The one included in \textbf{scikit-learn} is reduced data. The full data set is at \href{{https://www.kaggle.com/datasets/hojjatk/mnist-dataset}}{\nolinkurl{https://www.kaggle.com/datasets/hojjatk/mnist-dataset}}.
\end{enumerate}
\noindent
\end{itemize}
\noindent
We will start with a regression problem and we will reuse our codes on gradient descent methods from project 1.
\paragraph{Part a): Analytical warm-up.}
When using our gradient machinery from project 1, we will need the expressions for the cost/loss functions and their respective
gradients. The functions whose gradients we need are:
\begin{enumerate}
\item The mean-squared error (MSE) with and without the $L_1$ and $L_2$ norms (regression problems)
\item The binary cross entropy (aka log loss) for classification problems with and without $L_1$ and $L_2$ norms
\item The multiclass cross entropy cost/loss function (aka Softmax cross entropy or just Softmax loss function)
\end{enumerate}
\noindent
Set up these three cost/loss functions and their respective derivatives and explain the various terms.
We will test three activation functions for our neural network setup, these are the
\begin{enumerate}
\item The Sigmoid (aka \textbf{logit}) function,
\item the RELU function and
\item the Leaky RELU function
\end{enumerate}
\noindent
Set up their expressions and their first derivatives.
You may consult the lecture notes (with codes and more) from week 42 at \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}.
\paragraph{Reminder about the gradient machinery from project 1.}
In the setup of a neural network code you will need your gradient descent codes from
project 1. For neural networks we will recommend using stochastic
gradient descent with either the RMSprop or the ADAM algorithms for
updating the learning rates. But you should feel free to try plain gradient descent as well.
We recommend reading chapter 8 on optimization from the textbook of
Goodfellow, Bengio and Courville at
\href{{https://www.deeplearningbook.org/}}{\nolinkurl{https://www.deeplearningbook.org/}}. This chapter contains many
useful insights and discussions on the optimization part of machine
learning. A useful reference on the back progagation algorithm is
Nielsen's book at \href{{http://neuralnetworksanddeeplearning.com/}}{\nolinkurl{http://neuralnetworksanddeeplearning.com/}}.
You will find the Python \href{{https://seaborn.pydata.org/generated/seaborn.heatmap.html}}{Seaborn
package}
useful when plotting the results as function of the learning rate
$\eta$ and the hyper-parameter $\lambda$ .
\paragraph{Part b): Writing your own Neural Network code.}
Your aim now, and this is the central part of this project, is to
write your own FFNN code implementing the back
propagation algorithm discussed in the lecture slides from week 41 at \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html}} and week 42 at \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}.
We will focus on a regression problem first, using the one-dimensional Runge function
\[
f(x) = \frac{1}{1+25x^2},
\]
from project 1.
Use only the mean-squared error as cost function (no regularization terms) and
write an FFNN code for a regression problem with a flexible number of hidden
layers and nodes using only 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?
And how would you set up your design/feature matrix? Hint: does it have to represent a polynomial approximation as you did in project 1?
Train your network and compare the results with those from your OLS
regression code from project 1 using the one-dimensional Runge
function. When comparing your neural network code with the OLS
results from project 1, use the same data sets which gave you the best
MSE score. Moreover, use the polynomial order from project 1 that gave you the
best result. Compare these results with your neural network with one
and two hidden layers using $50$ and $100$ hidden nodes, respectively.
Comment your results and give a critical discussion of the results
obtained with the OLS code from project 1 and your own neural network
code. Make an analysis of the learning rates employed to find the
optimal MSE and $R2$ scores. Test both stochastic gradient descent
with RMSprop and ADAM and plain gradient descent with different
learning rates.
You should, as you did in project 1, scale your data.
\paragraph{Part c): Testing against other software libraries.}
You should test your results against a similar code using \textbf{Scikit-Learn} (see the examples in the above lecture notes from weeks 41 and 42) or \textbf{tensorflow/keras} or \textbf{Pytorch} (for Pytorch, see Raschka et al.'s text chapters 12 and 13).
Furthermore, you should also test that your derivatives are correctly
calculated using automatic differentiation, using for example the
\textbf{Autograd} library or the \textbf{JAX} library. It is optional to implement
these libraries for the present project. In this project they serve as
useful tests of our derivatives.
\paragraph{Part d): Testing different activation functions and depths of the neural network.}
You should also test different activation functions for the hidden
layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and
discuss your results. Test your results as functions of the number of hidden layers and nodes. Do you see signs of overfitting?
It is optional in this project to perform a bias-variance trade-off analysis.
\paragraph{Part e): Testing different norms.}
Finally, still using the one-dimensional Runge function, add now the
hyperparameters $\lambda$ with the $L_2$ and $L_1$ norms. Find the
optimal results for the hyperparameters $\lambda$ and the learning
rates $\eta$ and neural network architecture and compare the $L_2$ results with Ridge regression from
project 1 and the $L_1$ results with the Lasso calculations of project 1.
Use again the same data sets and the best results from project 1 in your comparisons.
\paragraph{Part f): Classification analysis using neural networks.}
With a well-written code it should now be easy to change the
activation function for the output layer.
Here we will change the cost function for our neural network code
developed in parts b), d) and e) in order to perform a classification
analysis. The classification problem we will study is the multiclass
MNIST problem, see the description of the full data set at
\href{{https://www.kaggle.com/datasets/hojjatk/mnist-dataset}}{\nolinkurl{https://www.kaggle.com/datasets/hojjatk/mnist-dataset}}. We will use the Softmax cross entropy function discussed in a).
The MNIST data set discussed in the lecture notes from week 42 is a downscaled variant of the full dataset.
Feel free to suggest other data sets. If you find the classic MNIST data set somewhat limited, feel free to try the
MNIST-Fashion data set at for example \href{{https://www.kaggle.com/datasets/zalando-research/fashionmnist}}{\nolinkurl{https://www.kaggle.com/datasets/zalando-research/fashionmnist}}.
To set up the data set, the following python programs may be useful
\bpycod
from sklearn.datasets import fetch_openml
# Fetch the MNIST dataset
mnist = fetch_openml('mnist_784', version=1, as_frame=False, parser='auto')
# Extract data (features) and target (labels)
X = mnist.data
y = mnist.target
\epycod
You should consider scaling the data. The Pixel values in MNIST range from 0 to 255. Scaling them to a 0-1 range can improve the performance of some models. That is, you could implement the following scaling
\bpycod
X = X / 255.0
\epycod
And then perform the standard train-test splitting
\bpycod
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
\epycod
To measure the performance of our classification problem we will use the
so-called \emph{accuracy} 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
\[
\text{Accuracy} = \frac{\sum_{i=1}^n I(t_i = y_i)}{n} ,
\]
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$.
Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter $\lambda$, various activation functions, number of hidden layers and nodes and activation functions.
Again, we strongly recommend that you compare your own neural Network
code for classification and pertinent results against a similar code using \textbf{Scikit-Learn} or \textbf{tensorflow/keras} or \textbf{pytorch}.
If you have time, you can use the functionality of \textbf{scikit-learn} and compare your neural network results with those from Logistic regression. This is optional.
The weblink here \href{{https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3}}{\nolinkurl{https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3}}compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article. Your neural network code can implement the equivalent of logistic regression by simply setting the number of hidden layers to zero.
If you wish to compare with say Logisti Regression from \textbf{scikit-learn}, the following code uses the above data set
\bpycod
from sklearn.linear_model import LogisticRegression
# Initialize the model
model = LogisticRegression(solver='saga', multi_class='multinomial', max_iter=1000, random_state=42)
# Train the model
model.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
# Make predictions on the test set
y_pred = model.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.4f}")
\epycod
\paragraph{Part g) Critical evaluation of the various algorithms.}
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.
\subsection{Background literature}
\begin{enumerate}
\item The text of Michael Nielsen is highly recommended, see Nielsen's book at \href{{http://neuralnetworksanddeeplearning.com/}}{\nolinkurl{http://neuralnetworksanddeeplearning.com/}}. It is an excellent read.
\item Goodfellow, Bengio and Courville, Deep Learning at \href{{https://www.deeplearningbook.org/}}{\nolinkurl{https://www.deeplearningbook.org/}}. Here we recommend chapters 6, 7 and 8
\item Raschka et al.~at \href{{https://sebastianraschka.com/blog/2022/ml-pytorch-book.html}}{\nolinkurl{https://sebastianraschka.com/blog/2022/ml-pytorch-book.html}}. Here we recommend chapters 11, 12 and 13.
\end{enumerate}
\noindent
\subsection{Introduction to numerical projects}
Here follows a brief recipe and recommendation on how to write a report for each
project.
\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.
\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 or Python. The following prescription should be followed when preparing the report:
\begin{itemize}
\item Use Canvas to hand in your projects, log in at \href{{https://www.uio.no/english/services/it/education/canvas/}}{\nolinkurl{https://www.uio.no/english/services/it/education/canvas/}} with your normal UiO username and password.
\item Upload \textbf{only} 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.
\item 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.
\end{itemize}
\noindent
Finally,
we encourage you to collaborate. Optimal working groups consist of
2-3 students. You can then hand in a common report.
% ------------------- end of main content ---------------
% #ifdef PREAMBLE
\end{document}
% #endif
+510
View File
@@ -0,0 +1,510 @@
%%
%% Automatically generated file from DocOnce source
%% (https://github.com/doconce/doconce/)
%% doconce format latex Project2.do.txt --print_latex_style=trac --latex_admon=paragraph
%%
%-------------------- begin preamble ----------------------
\documentclass[%
oneside, % oneside: electronic viewing, twoside: printing
final, % draft: marks overfull hboxes, figures with paths
10pt]{article}
\listfiles % print all files needed to compile this document
\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb}
\usepackage[table]{xcolor}
\usepackage{bm,ltablex,microtype}
\usepackage[pdftex]{graphicx}
\usepackage{fancyvrb} % packages needed for verbatim environments
\usepackage[T1]{fontenc}
%\usepackage[latin1]{inputenc}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern
% Hyperlinks in PDF:
\definecolor{linkcolor}{rgb}{0,0,0.4}
\usepackage{hyperref}
\hypersetup{
breaklinks=true,
colorlinks=true,
linkcolor=linkcolor,
urlcolor=linkcolor,
citecolor=black,
filecolor=black,
%filecolor=blue,
pdfmenubar=true,
pdftoolbar=true,
bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC
}
%\hyperbaseurl{} % hyperlinks are relative to this root
\setcounter{tocdepth}{2} % levels in table of contents
% --- fancyhdr package for fancy headers ---
\usepackage{fancyhdr}
\fancyhf{} % sets both header and footer to nothing
\renewcommand{\headrulewidth}{0pt}
\fancyfoot[LE,RO]{\thepage}
% Ensure copyright on titlepage (article style) and chapter pages (book style)
\fancypagestyle{plain}{
\fancyhf{}
\fancyfoot[C]{{\footnotesize \copyright\ 1999-2025, "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}}
% \renewcommand{\footrulewidth}{0mm}
\renewcommand{\headrulewidth}{0mm}
}
% Ensure copyright on titlepages with \thispagestyle{empty}
\fancypagestyle{empty}{
\fancyhf{}
\fancyfoot[C]{{\footnotesize \copyright\ 1999-2025, "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}}
\renewcommand{\footrulewidth}{0mm}
\renewcommand{\headrulewidth}{0mm}
}
\pagestyle{fancy}
% prevent orhpans and widows
\clubpenalty = 10000
\widowpenalty = 10000
% --- end of standard preamble for documents ---
% insert custom LaTeX commands...
\raggedbottom
\makeindex
\usepackage[totoc]{idxlayout} % for index in the toc
\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc
%-------------------- end preamble ----------------------
\begin{document}
% matching end for #ifdef PREAMBLE
\newcommand{\exercisesection}[1]{\subsection*{#1}}
% ------------------- main content ----------------------
% ----------------- title -------------------------
\thispagestyle{empty}
\begin{center}
{\LARGE\bf
\begin{spacing}{1.25}
Project 2 on Machine Learning, deadline November 10 (Midnight)
\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}
October 14, 2025
\end{center}
% --- end date ---
\vspace{1cm}
\subsection*{Deliverables}
First, join a group in canvas with your group partners. Pick an avaliable group for Project 2 in the \textbf{People} page.
In canvas, deliver as a group and include:
\begin{itemize}
\item A PDF of your report which follows the guidelines covered below and in the week 39 exercises. Additional requirements include:
\begin{itemize}
\item It should be around 5000 words, use the word counter in Overleaf for this. This often corresponds to 10-12 pages. References and appendices are excluded from the word count
\item It should include around 10-15 figures. You can include more figures in appendices and/or as supplemental material in your repository.
\end{itemize}
\noindent
\item A comment linking to your github repository (or folder in one of your github repositories) for this project. The repository must include
\end{itemize}
\noindent
A PDF file of the report
\begin{itemize}
\item A folder named Code, where you put python files for your functions and notebooks for reproducing your results. Remember to use a seed for generating random data and for train-test splits when generating final results.
\item A README file with the name of the group members
\item a short description of the project
\item a description of how to install the required packages to run your code from a requirements.txt file or similar (such as a plain text description) names and descriptions of the various notebooks in the Code folder and the results they produce
\end{itemize}
\noindent
\paragraph{Preamble: Note on writing reports, using reference material, AI and other tools.}
We want you to answer the three different projects by handing in
reports written like a standard scientific/technical report. The links
at
https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects
contain more information. There you can find examples of previous
reports, the projects themselves, how we grade reports etc. How to
write reports will also be discussed during the various lab
sessions. Please do ask us if you are in doubt.
When using codes and material from other sources, you should refer to
these in the bibliography of your report, indicating wherefrom you for
example got the code, whether this is from the lecture notes,
softwares like Scikit-Learn, TensorFlow, PyTorch or other
sources. These sources should always be cited correctly. How to cite
some of the libraries is often indicated from their corresponding
GitHub sites or websites, see for example how to cite Scikit-Learn at
https://scikit-learn.org/dev/about.html.
We enocurage you to use tools like ChatGPT or similar in writing the
report. If you use for example ChatGPT, please do cite it properly and
include (if possible) your questions and answers as an addition to the
report. This can be uploaded to for example your website,
GitHub/GitLab or similar as supplemental material.
If you would like to study other data sets, feel free to propose other
sets. What we have proposed 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
https://archive.ics.uci.edu/ml/index.php is an excellent site to look
up for examples and inspiration. Kaggle.com is an equally interesting
site. Feel free to explore these sites.
\subsection*{Classification and Regression, writing our own neural network code}
The main aim of this project is to study both classification and
regression problems by developing our own
feed-forward neural network (FFNN) code. The exercises from week 41 and 42 (see \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html}} and \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html}}) as well as the lecture material from the same weeks (see \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html}} and \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}) should contain enough information for you to get started with writing your own code.
We will also reuse our codes on gradient descent methods from project 1.
The data sets that we propose here are (the default sets)
\begin{itemize}
\item 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
\begin{enumerate}
\item The simple one-dimensional function Runge function from project 1, that is $f(x) = \frac{1}{1+25x^2}$. We recommend using a simpler function when developing your neural network code for regression problems. You should however feel free to discuss and study other functions, such as the the two-dimensional Runge function $f(x,y)=\left[(10x - 5)^2 + (10y - 5)^2 + 1 \right]^{-1}$, or even more complicated two-dimensional functions (see the supplementary material of \href{{https://www.nature.com/articles/s41467-025-61362-4}}{\nolinkurl{https://www.nature.com/articles/s41467-025-61362-4}} for an extensive list of two-dimensional functions).
\end{enumerate}
\noindent
\item Classification.
\begin{enumerate}
\item We will consider the multiclass classification problem given by the full MNIST data set. The one included in \textbf{scikit-learn} is reduced data. The full data set is at \href{{https://www.kaggle.com/datasets/hojjatk/mnist-dataset}}{\nolinkurl{https://www.kaggle.com/datasets/hojjatk/mnist-dataset}}.
\end{enumerate}
\noindent
\end{itemize}
\noindent
We will start with a regression problem and we will reuse our codes on gradient descent methods from project 1.
\paragraph{Part a): Analytical warm-up.}
When using our gradient machinery from project 1, we will need the expressions for the cost/loss functions and their respective
gradients. The functions whose gradients we need are:
\begin{enumerate}
\item The mean-squared error (MSE) with and without the $L_1$ and $L_2$ norms (regression problems)
\item The binary cross entropy (aka log loss) for classification problems with and without $L_1$ and $L_2$ norms
\item The multiclass cross entropy cost/loss function (aka Softmax cross entropy or just Softmax loss function)
\end{enumerate}
\noindent
Set up these three cost/loss functions and their respective derivatives and explain the various terms.
We will test three activation functions for our neural network setup, these are the
\begin{enumerate}
\item The Sigmoid (aka \textbf{logit}) function,
\item the RELU function and
\item the Leaky RELU function
\end{enumerate}
\noindent
Set up their expressions and their first derivatives.
You may consult the lecture notes (with codes and more) from week 42 at \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}.
\paragraph{Reminder about the gradient machinery from project 1.}
In the setup of a neural network code you will need your gradient descent codes from
project 1. For neural networks we will recommend using stochastic
gradient descent with either the RMSprop or the ADAM algorithms for
updating the learning rates. But you should feel free to try plain gradient descent as well.
We recommend reading chapter 8 on optimization from the textbook of
Goodfellow, Bengio and Courville at
\href{{https://www.deeplearningbook.org/}}{\nolinkurl{https://www.deeplearningbook.org/}}. This chapter contains many
useful insights and discussions on the optimization part of machine
learning. A useful reference on the back progagation algorithm is
Nielsen's book at \href{{http://neuralnetworksanddeeplearning.com/}}{\nolinkurl{http://neuralnetworksanddeeplearning.com/}}.
You will find the Python \href{{https://seaborn.pydata.org/generated/seaborn.heatmap.html}}{Seaborn
package}
useful when plotting the results as function of the learning rate
$\eta$ and the hyper-parameter $\lambda$ .
\paragraph{Part b): Writing your own Neural Network code.}
Your aim now, and this is the central part of this project, is to
write your own FFNN code implementing the back
propagation algorithm discussed in the lecture slides from week 41 at \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html}} and week 42 at \href{{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}{\nolinkurl{https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html}}.
We will focus on a regression problem first, using the one-dimensional Runge function
\[
f(x) = \frac{1}{1+25x^2},
\]
from project 1.
Use only the mean-squared error as cost function (no regularization terms) and
write an FFNN code for a regression problem with a flexible number of hidden
layers and nodes using only 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?
And how would you set up your design/feature matrix? Hint: does it have to represent a polynomial approximation as you did in project 1?
Train your network and compare the results with those from your OLS
regression code from project 1 using the one-dimensional Runge
function. When comparing your neural network code with the OLS
results from project 1, use the same data sets which gave you the best
MSE score. Moreover, use the polynomial order from project 1 that gave you the
best result. Compare these results with your neural network with one
and two hidden layers using $50$ and $100$ hidden nodes, respectively.
Comment your results and give a critical discussion of the results
obtained with the OLS code from project 1 and your own neural network
code. Make an analysis of the learning rates employed to find the
optimal MSE and $R2$ scores. Test both stochastic gradient descent
with RMSprop and ADAM and plain gradient descent with different
learning rates.
You should, as you did in project 1, scale your data.
\paragraph{Part c): Testing against other software libraries.}
You should test your results against a similar code using \textbf{Scikit-Learn} (see the examples in the above lecture notes from weeks 41 and 42) or \textbf{tensorflow/keras} or \textbf{Pytorch} (for Pytorch, see Raschka et al.'s text chapters 12 and 13).
Furthermore, you should also test that your derivatives are correctly
calculated using automatic differentiation, using for example the
\textbf{Autograd} library or the \textbf{JAX} library. It is optional to implement
these libraries for the present project. In this project they serve as
useful tests of our derivatives.
\paragraph{Part d): Testing different activation functions and depths of the neural network.}
You should also test different activation functions for the hidden
layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and
discuss your results. Test your results as functions of the number of hidden layers and nodes. Do you see signs of overfitting?
It is optional in this project to perform a bias-variance trade-off analysis.
\paragraph{Part e): Testing different norms.}
Finally, still using the one-dimensional Runge function, add now the
hyperparameters $\lambda$ with the $L_2$ and $L_1$ norms. Find the
optimal results for the hyperparameters $\lambda$ and the learning
rates $\eta$ and neural network architecture and compare the $L_2$ results with Ridge regression from
project 1 and the $L_1$ results with the Lasso calculations of project 1.
Use again the same data sets and the best results from project 1 in your comparisons.
\paragraph{Part f): Classification analysis using neural networks.}
With a well-written code it should now be easy to change the
activation function for the output layer.
Here we will change the cost function for our neural network code
developed in parts b), d) and e) in order to perform a classification
analysis. The classification problem we will study is the multiclass
MNIST problem, see the description of the full data set at
\href{{https://www.kaggle.com/datasets/hojjatk/mnist-dataset}}{\nolinkurl{https://www.kaggle.com/datasets/hojjatk/mnist-dataset}}. We will use the Softmax cross entropy function discussed in a).
The MNIST data set discussed in the lecture notes from week 42 is a downscaled variant of the full dataset.
Feel free to suggest other data sets. If you find the classic MNIST data set somewhat limited, feel free to try the
MNIST-Fashion data set at for example \href{{https://www.kaggle.com/datasets/zalando-research/fashionmnist}}{\nolinkurl{https://www.kaggle.com/datasets/zalando-research/fashionmnist}}.
To set up the data set, the following python programs may be useful
\begin{verbatim}
from sklearn.datasets import fetch_openml
# Fetch the MNIST dataset
mnist = fetch_openml('mnist_784', version=1, as_frame=False, parser='auto')
# Extract data (features) and target (labels)
X = mnist.data
y = mnist.target
\end{verbatim}
You should consider scaling the data. The Pixel values in MNIST range from 0 to 255. Scaling them to a 0-1 range can improve the performance of some models. That is, you could implement the following scaling
\begin{verbatim}
X = X / 255.0
\end{verbatim}
And then perform the standard train-test splitting
\begin{verbatim}
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
\end{verbatim}
To measure the performance of our classification problem we will use the
so-called \emph{accuracy} 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
\[
\text{Accuracy} = \frac{\sum_{i=1}^n I(t_i = y_i)}{n} ,
\]
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$.
Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter $\lambda$, various activation functions, number of hidden layers and nodes and activation functions.
Again, we strongly recommend that you compare your own neural Network
code for classification and pertinent results against a similar code using \textbf{Scikit-Learn} or \textbf{tensorflow/keras} or \textbf{pytorch}.
If you have time, you can use the functionality of \textbf{scikit-learn} and compare your neural network results with those from Logistic regression. This is optional.
The weblink here \href{{https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3}}{\nolinkurl{https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3}}compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article. Your neural network code can implement the equivalent of logistic regression by simply setting the number of hidden layers to zero.
If you wish to compare with say Logisti Regression from \textbf{scikit-learn}, the following code uses the above data set
\begin{verbatim}
from sklearn.linear_model import LogisticRegression
# Initialize the model
model = LogisticRegression(solver='saga', multi_class='multinomial', max_iter=1000, random_state=42)
# Train the model
model.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
# Make predictions on the test set
y_pred = model.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.4f}")
\end{verbatim}
\paragraph{Part g) Critical evaluation of the various algorithms.}
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.
\subsection*{Background literature}
\begin{enumerate}
\item The text of Michael Nielsen is highly recommended, see Nielsen's book at \href{{http://neuralnetworksanddeeplearning.com/}}{\nolinkurl{http://neuralnetworksanddeeplearning.com/}}. It is an excellent read.
\item Goodfellow, Bengio and Courville, Deep Learning at \href{{https://www.deeplearningbook.org/}}{\nolinkurl{https://www.deeplearningbook.org/}}. Here we recommend chapters 6, 7 and 8
\item Raschka et al.~at \href{{https://sebastianraschka.com/blog/2022/ml-pytorch-book.html}}{\nolinkurl{https://sebastianraschka.com/blog/2022/ml-pytorch-book.html}}. Here we recommend chapters 11, 12 and 13.
\end{enumerate}
\noindent
\subsection*{Introduction to numerical projects}
Here follows a brief recipe and recommendation on how to write a report for each
project.
\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.
\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 or Python. The following prescription should be followed when preparing the report:
\begin{itemize}
\item Use Canvas to hand in your projects, log in at \href{{https://www.uio.no/english/services/it/education/canvas/}}{\nolinkurl{https://www.uio.no/english/services/it/education/canvas/}} with your normal UiO username and password.
\item Upload \textbf{only} 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.
\item 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.
\end{itemize}
\noindent
Finally,
we encourage you to collaborate. Optimal working groups consist of
2-3 students. You can then hand in a common report.
% ------------------- end of main content ---------------
\end{document}
@@ -0,0 +1,555 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "aa8cd4fa",
"metadata": {
"editable": true
},
"source": [
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
"doconce format html Project2.do.txt -->\n",
"<!-- dom:TITLE: Project 2 on Machine Learning, deadline November 10 (Midnight) -->"
]
},
{
"cell_type": "markdown",
"id": "5f1135b4",
"metadata": {
"editable": true
},
"source": [
"# Project 2 on Machine Learning, deadline November 10 (Midnight)\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: **October 14, 2025**"
]
},
{
"cell_type": "markdown",
"id": "887ae589",
"metadata": {
"editable": true
},
"source": [
"## Deliverables\n",
"\n",
"First, join a group in canvas with your group partners. Pick an avaliable group for Project 2 in the **People** page.\n",
"\n",
"In canvas, deliver as a group and include:\n",
"\n",
"* A PDF of your report which follows the guidelines covered below and in the week 39 exercises. Additional requirements include:\n",
"\n",
" * It should be around 5000 words, use the word counter in Overleaf for this. This often corresponds to 10-12 pages. References and appendices are excluded from the word count\n",
"\n",
" * It should include around 10-15 figures. You can include more figures in appendices and/or as supplemental material in your repository.\n",
"\n",
"* A comment linking to your github repository (or folder in one of your github repositories) for this project. The repository must include\n",
"\n",
"A PDF file of the report\n",
" * A folder named Code, where you put python files for your functions and notebooks for reproducing your results. Remember to use a seed for generating random data and for train-test splits when generating final results.\n",
"\n",
" * A README file with the name of the group members\n",
"\n",
" * a short description of the project\n",
"\n",
" * a description of how to install the required packages to run your code from a requirements.txt file or similar (such as a plain text description) names and descriptions of the various notebooks in the Code folder and the results they produce"
]
},
{
"cell_type": "markdown",
"id": "2abeb4c0",
"metadata": {
"editable": true
},
"source": [
"### Preamble: Note on writing reports, using reference material, AI and other tools\n",
"\n",
"We want you to answer the three different projects by handing in\n",
"reports written like a standard scientific/technical report. The links\n",
"at\n",
"https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects\n",
"contain more information. There you can find examples of previous\n",
"reports, the projects themselves, how we grade reports etc. How to\n",
"write reports will also be discussed during the various lab\n",
"sessions. Please do ask us if you are in doubt.\n",
"\n",
"When using codes and material from other sources, you should refer to\n",
"these in the bibliography of your report, indicating wherefrom you for\n",
"example got the code, whether this is from the lecture notes,\n",
"softwares like Scikit-Learn, TensorFlow, PyTorch or other\n",
"sources. These sources should always be cited correctly. How to cite\n",
"some of the libraries is often indicated from their corresponding\n",
"GitHub sites or websites, see for example how to cite Scikit-Learn at\n",
"https://scikit-learn.org/dev/about.html.\n",
"\n",
"We enocurage you to use tools like ChatGPT or similar in writing the\n",
"report. If you use for example ChatGPT, please do cite it properly and\n",
"include (if possible) your questions and answers as an addition to the\n",
"report. This can be uploaded to for example your website,\n",
"GitHub/GitLab or similar as supplemental material.\n",
"\n",
"If you would like to study other data sets, feel free to propose other\n",
"sets. What we have proposed here are mere suggestions from our\n",
"side. If you opt for another data set, consider using a set which has\n",
"been studied in the scientific literature. This makes it easier for\n",
"you to compare and analyze your results. Comparing with existing\n",
"results from the scientific literature is also an essential element of\n",
"the scientific discussion. The University of California at Irvine with\n",
"its Machine Learning repository at\n",
"https://archive.ics.uci.edu/ml/index.php is an excellent site to look\n",
"up for examples and inspiration. Kaggle.com is an equally interesting\n",
"site. Feel free to explore these sites."
]
},
{
"cell_type": "markdown",
"id": "120fde91",
"metadata": {
"editable": true
},
"source": [
"## Classification and Regression, writing our own neural network code\n",
"\n",
"The main aim of this project is to study both classification and\n",
"regression problems by developing our own feed-forward neural network\n",
"(FFNN) code. The exercises from week 41 and 42 (see <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html> and <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html>) as well as the lecture material from the same weeks (see <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html> and <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html>) should contain enough information for you to get started with writing your own code.\n",
"\n",
"We will also reuse our codes on gradient descent methods from project 1.\n",
"\n",
"The data sets that we propose here are (the default sets)\n",
"\n",
"* 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\n",
"\n",
"a. The simple one-dimensional function Runge function from project 1, that is $f(x) = \\frac{1}{1+25x^2}$. We recommend using a simpler function when developing your neural network code for regression problems. You should however feel free to discuss and study other functions, such as the the two-dimensional Runge function $f(x,y)=\\left[(10x - 5)^2 + (10y - 5)^2 + 1 \\right]^{-1}$, or even more complicated two-dimensional functions (see the supplementary material of <https://www.nature.com/articles/s41467-025-61362-4> for an extensive list of two-dimensional functions. We leave this however as an option for project 3. \n",
"\n",
"* Classification.\n",
"\n",
"a. We will consider the multiclass classification problem given by the full MNIST data set. The one included in **scikit-learn** is reduced data. The full data set is at <https://www.kaggle.com/datasets/hojjatk/mnist-dataset>. \n",
"\n",
"We will start with a regression problem and we will reuse our codes on gradient descent methods from project 1."
]
},
{
"cell_type": "markdown",
"id": "ed46ed5e",
"metadata": {
"editable": true
},
"source": [
"### Part a): Analytical warm-up\n",
"\n",
"When using our gradient machinery from project 1, we will need the expressions for the cost/loss functions and their respective\n",
"gradients. The functions whose gradients we need are:\n",
"1. The mean-squared error (MSE) with and without the $L_1$ and $L_2$ norms (regression problems)\n",
"\n",
"2. The binary cross entropy (aka log loss) for classification problems with and without $L_1$ and $L_2$ norms\n",
"\n",
"3. The multiclass cross entropy cost/loss function (aka Softmax cross entropy or just Softmax loss function)\n",
"\n",
"Set up these three cost/loss functions and their respective derivatives and explain the various terms.\n",
"\n",
"We will test three activation functions for our neural network setup, these are the \n",
"1. The Sigmoid (aka **logit**) function,\n",
"\n",
"2. the RELU function and\n",
"\n",
"3. the Leaky RELU function\n",
"\n",
"Set up their expressions and their first derivatives.\n",
"You may consult the lecture notes (with codes and more) from week 42 at <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html>."
]
},
{
"cell_type": "markdown",
"id": "89a608b3",
"metadata": {
"editable": true
},
"source": [
"### Reminder about the gradient machinery from project 1\n",
"\n",
"In the setup of a neural network code you will need your gradient descent codes from\n",
"project 1. For neural networks we will recommend using stochastic\n",
"gradient descent with either the RMSprop or the ADAM algorithms for\n",
"updating the learning rates. But you should feel free to try plain gradient descent as well.\n",
"\n",
"We recommend reading chapter 8 on optimization from the textbook of\n",
"Goodfellow, Bengio and Courville at\n",
"<https://www.deeplearningbook.org/>. This chapter contains many\n",
"useful insights and discussions on the optimization part of machine\n",
"learning. A useful reference on the back progagation algorithm is\n",
"Nielsen's book at <http://neuralnetworksanddeeplearning.com/>. It\n",
"is an excellent\n",
"\n",
"You will find the Python [Seaborn\n",
"package](https://seaborn.pydata.org/generated/seaborn.heatmap.html)\n",
"useful when plotting the results as function of the learning rate\n",
"$\\eta$ and the hyper-parameter $\\lambda$ ."
]
},
{
"cell_type": "markdown",
"id": "efae04b0",
"metadata": {
"editable": true
},
"source": [
"### Part b): Writing your own Neural Network code\n",
"\n",
"Your aim now, and this is the central part of this project, is to\n",
"write your own Feed Forward Neural Network code implementing the back\n",
"propagation algorithm discussed in the lecture slides from week 41 at <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html> and week 42 at <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html>.\n",
"\n",
"We will focus on a regression problem first, using the one-dimensional Runge function"
]
},
{
"cell_type": "markdown",
"id": "21420400",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"f(x) = \\frac{1}{1+25x^2},\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "c0f204ea",
"metadata": {
"editable": true
},
"source": [
"from project 1.\n",
"\n",
"Use only the mean-squared error as cost function (no regularization terms) and \n",
"write an FFNN code for a regression problem with a flexible number of hidden\n",
"layers and nodes using only the Sigmoid function as activation function for\n",
"the hidden layers. Initialize the weights using a normal\n",
"distribution. How would you initialize the biases? And which\n",
"activation function would you select for the final output layer?\n",
"And how would you set up your design/feature matrix? Hint: does it have to represent a polynomial approximation as you did in project 1? \n",
"\n",
"Train your network and compare the results with those from your OLS\n",
"regression code from project 1 using the one-dimensional Runge\n",
"function. When comparing your neural network code with the OLS\n",
"results from project 1, use the same data sets which gave you the best\n",
"MSE score. Moreover, use the polynomial order from project 1 that gave you the\n",
"best result. Compare these results with your neural network with one\n",
"and two hidden layers using $50$ and $100$ hidden nodes, respectively.\n",
"\n",
"Comment your results and give a critical discussion of the results\n",
"obtained with the OLS code from project 1 and your own neural network\n",
"code. Make an analysis of the learning rates employed to find the\n",
"optimal MSE and $R2$ scores. Test both stochastic gradient descent\n",
"with RMSprop and ADAM and plain gradient descent with different\n",
"learning rates.\n",
"\n",
"You should, as you did in project 1, scale your data."
]
},
{
"cell_type": "markdown",
"id": "fb5eb86a",
"metadata": {
"editable": true
},
"source": [
"### Part c): Testing against other software libraries\n",
"\n",
"You should test your results against a similar code using **Scikit-Learn** (see the examples in the above lecture notes from weeks 41 and 42) or **tensorflow/keras** or **Pytorch** (for Pytorch, see Raschka et al.'s text chapters 12 and 13). \n",
"\n",
"Furthermore, you should also test that your derivatives are correctly\n",
"calculated using automatic differentiation, using for example the\n",
"**Autograd** library or the **JAX** library. It is optional to implement\n",
"these libraries for the present project. In this project they serve as\n",
"useful tests of our derivatives."
]
},
{
"cell_type": "markdown",
"id": "31f28df1",
"metadata": {
"editable": true
},
"source": [
"### Part d): Testing different activation functions and depths of the neural network\n",
"\n",
"You should also test different activation functions for the hidden\n",
"layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and\n",
"discuss your results. Test your results as functions of the number of hidden layers and nodes. Do you see signs of overfitting?\n",
"It is optional in this project to perform a bias-variance trade-off analysis."
]
},
{
"cell_type": "markdown",
"id": "42234a78",
"metadata": {
"editable": true
},
"source": [
"### Part e): Testing different norms\n",
"\n",
"Finally, still using the one-dimensional Runge function, add now the\n",
"hyperparameters $\\lambda$ with the $L_2$ and $L_1$ norms. Find the\n",
"optimal results for the hyperparameters $\\lambda$ and the learning\n",
"rates $\\eta$ and neural network architecture and compare the $L_2$ results with Ridge regression from\n",
"project 1 and the $L_1$ results with the Lasso calculations of project\n",
"1. Use again the same data sets and the best results from project 1 in your comparisons."
]
},
{
"cell_type": "markdown",
"id": "3293c0df",
"metadata": {
"editable": true
},
"source": [
"### Part f): Classification analysis using neural networks\n",
"\n",
"With a well-written code it should now be easy to change the\n",
"activation function for the output layer.\n",
"\n",
"Here we will change the cost function for our neural network code\n",
"developed in parts b), d) and e) in order to perform a classification\n",
"analysis. The classification problem we will study is the multiclass\n",
"MNIST problem, see the description of the full data set at\n",
"<https://www.kaggle.com/datasets/hojjatk/mnist-dataset>. We will use the Softmax cross entropy function discussed in a). \n",
"The MNIST data set discussed in the lecture notes from week 42, is a downscaled variant of the full dataset. \n",
"\n",
"Feel free to suggest other data sets. If you find the classic MNIST data set somewhat limited, feel free to try the \n",
"MNIST-Fashion data set at for example <https://www.kaggle.com/datasets/zalando-research/fashionmnist>.\n",
"\n",
"To set up the data set, the following python programs may be useful"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "4ef36899",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.datasets import fetch_openml\n",
"\n",
"# Fetch the MNIST dataset\n",
"mnist = fetch_openml('mnist_784', version=1, as_frame=False, parser='auto')\n",
"\n",
"# Extract data (features) and target (labels)\n",
"X = mnist.data\n",
"y = mnist.target"
]
},
{
"cell_type": "markdown",
"id": "1215ffb1",
"metadata": {
"editable": true
},
"source": [
"You should consider scaling the data. The Pixel values in MNIST range from 0 to 255. Scaling them to a 0-1 range can improve the performance of some models. That is, you could implement the following scaling"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "799c6d08",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"X = X / 255.0"
]
},
{
"cell_type": "markdown",
"id": "e0bd8c49",
"metadata": {
"editable": true
},
"source": [
"And then perform the standard train-test splitting"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "71940eed",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
]
},
{
"cell_type": "markdown",
"id": "35e45fb9",
"metadata": {
"editable": true
},
"source": [
"To measure the performance of our classification problem we will use the\n",
"so-called *accuracy* score. The accuracy is as you would expect just\n",
"the number of correctly guessed targets $t_i$ divided by the total\n",
"number of targets, that is"
]
},
{
"cell_type": "markdown",
"id": "8ce9d737",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\text{Accuracy} = \\frac{\\sum_{i=1}^n I(t_i = y_i)}{n} ,\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "d5a473c6",
"metadata": {
"editable": true
},
"source": [
"where $I$ is the indicator function, $1$ if $t_i = y_i$ and $0$\n",
"otherwise if we have a binary classification problem. Here $t_i$\n",
"represents the target and $y_i$ the outputs of your FFNN code and $n$ is simply the number of targets $t_i$.\n",
"\n",
"Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter $\\lambda$, various activation functions, number of hidden layers and nodes and activation functions. \n",
"\n",
"Again, we strongly recommend that you compare your own neural Network\n",
"code for classification and pertinent results against a similar code using **Scikit-Learn** or **tensorflow/keras** or **pytorch**.\n",
"\n",
"If you have time, you can use the functionality of **scikit-learn** and compare your neural network results with those from Logistic regression. This is optional.\n",
"The weblink here <https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3>compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article. Your neural network code can implement the equivalent of logistic regression by simply setting the number of hidden layers to zero. \n",
"\n",
"If you wish to compare with say Logisti Regression from **scikit-learn**, the following code uses the above data set"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "03436ae6",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.linear_model import LogisticRegression\n",
"# Initialize the model\n",
"model = LogisticRegression(solver='saga', multi_class='multinomial', max_iter=1000, random_state=42)\n",
"# Train the model\n",
"model.fit(X_train, y_train)\n",
"from sklearn.metrics import accuracy_score\n",
"# Make predictions on the test set\n",
"y_pred = model.predict(X_test)\n",
"# Calculate accuracy\n",
"accuracy = accuracy_score(y_test, y_pred)\n",
"print(f\"Model Accuracy: {accuracy:.4f}\")"
]
},
{
"cell_type": "markdown",
"id": "45eefe11",
"metadata": {
"editable": true
},
"source": [
"### Part g) Critical evaluation of the various algorithms\n",
"\n",
"After all these glorious calculations, you should now summarize the\n",
"various algorithms and come with a critical evaluation of their pros\n",
"and cons. Which algorithm works best for the regression case and which\n",
"is best for the classification case. These codes can also be part of\n",
"your final project 3, but now applied to other data sets."
]
},
{
"cell_type": "markdown",
"id": "b8109105",
"metadata": {
"editable": true
},
"source": [
"## Background literature\n",
"\n",
"1. The text of Michael Nielsen is highly recommended, see Nielsen's book at <http://neuralnetworksanddeeplearning.com/>. It is an excellent read.\n",
"\n",
"2. Goodfellow, Bengio and Courville, Deep Learning at <https://www.deeplearningbook.org/>. Here we recommend chapters 6, 7 and 8\n",
"\n",
"3. Raschka et al. at <https://sebastianraschka.com/blog/2022/ml-pytorch-book.html>. Here we recommend chapters 11, 12 and 13."
]
},
{
"cell_type": "markdown",
"id": "f2ef8297",
"metadata": {
"editable": true
},
"source": [
"## Introduction to numerical projects\n",
"\n",
"Here follows a brief recipe and recommendation on how to write a report for each\n",
"project.\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.\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": "02555ef2",
"metadata": {
"editable": true
},
"source": [
"## Format for electronic delivery of report and programs\n",
"\n",
"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:\n",
"\n",
" * Use Canvas to hand in your projects, log in at <https://www.uio.no/english/services/it/education/canvas/> with your normal UiO username and password.\n",
"\n",
" * Upload **only** 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.\n",
"\n",
" * 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.\n",
"\n",
"Finally, \n",
"we encourage you to collaborate. Optimal working groups consist of \n",
"2-3 students. You can then hand in a common report."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
+205 -111
View File
@@ -1,144 +1,241 @@
TITLE: Project 2 on Machine Learning, deadline November 4 (Midnight)
AUTHOR: "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo, Norway
DATE: today
TITLE: Project 2 on Machine Learning, deadline November 10 (Midnight)
AUTHOR: "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" {copyright, 1999-present|CC BY-NC} at University of Oslo, Norway
DATE: October 14, 2025
===== Classification and Regression, from linear and logistic regression to neural networks =====
===== Deliverables =====
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 _and/or_ 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.
First, join a group in canvas with your group partners. Pick an avaliable group for Project 2 in the _People_ page.
In canvas, deliver as a group and include:
* A PDF of your report which follows the guidelines covered below and in the week 39 exercises. Additional requirements include:
* It should be around 5000 words, use the word counter in Overleaf for this. This often corresponds to 10-12 pages. References and appendices are excluded from the word count
* It should include around 10-15 figures. You can include more figures in appendices and/or as supplemental material in your repository.
* A comment linking to your github repository (or folder in one of your github repositories) for this project. The repository must include
A PDF file of the report
* A folder named Code, where you put python files for your functions and notebooks for reproducing your results. Remember to use a seed for generating random data and for train-test splits when generating final results.
* A README file with the name of the group members
* a short description of the project
* a description of how to install the required packages to run your code from a requirements.txt file or similar (such as a plain text description) names and descriptions of the various notebooks in the Code folder and the results they produce
The data sets that we propose here are (the default sets)
* 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
o 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.
* 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 "Wisconsin Breat Cancer Data":"https://www.kaggle.com/uciml/breast-cancer-wisconsin-data" data set of images representing various features of tumors. A longer explanation with links to the scientific literature can be found at the "Machine Learning repository of the University of California at Irvine":"https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Diagnostic%29". Feel free to consult this site and the pertinent literature.
You can find more information about this at the "Scikit-Learn site":"https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html" or at the "University of California at Irvine":"https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)".
=== Preamble: Note on writing reports, using reference material, AI and other tools ===
We want you to answer the three different projects by handing in
reports written like a standard scientific/technical report. The links
at
https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects
contain more information. There you can find examples of previous
reports, the projects themselves, how we grade reports etc. How to
write reports will also be discussed during the various lab
sessions. Please do ask us if you are in doubt.
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
When using codes and material from other sources, you should refer to
these in the bibliography of your report, indicating wherefrom you for
example got the code, whether this is from the lecture notes,
softwares like Scikit-Learn, TensorFlow, PyTorch or other
sources. These sources should always be cited correctly. How to cite
some of the libraries is often indicated from their corresponding
GitHub sites or websites, see for example how to cite Scikit-Learn at
https://scikit-learn.org/dev/about.html.
We enocurage you to use tools like ChatGPT or similar in writing the
report. If you use for example ChatGPT, please do cite it properly and
include (if possible) your questions and answers as an addition to the
report. This can be uploaded to for example your website,
GitHub/GitLab or similar as supplemental material.
If you would like to study other data sets, feel free to propose other
sets. What we have proposed 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
URL:"https://archive.ics.uci.edu/ml/index.php" is an excellent site to
look up for examples and
inspiration. "Kaggle.com":"https://www.kaggle.com/" is an equally
interesting site. Feel free to explore these sites.
the scientific discussion. The University of California at Irvine with
its Machine Learning repository at
https://archive.ics.uci.edu/ml/index.php is an excellent site to look
up for examples and inspiration. Kaggle.com is an equally interesting
site. Feel free to explore these sites.
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.
=== Part a): Write your own Stochastic Gradient Descent code, first step ===
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. _However, we recommend using a simpler function like_
$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.
The exercise set for week 41 should help in solving this part of the project.
You should include in your analysis of the GD and SGD codes the following elements
o A plain gradient descent with a fixed learning rate (you will need to tune it) using the analytical expression for the gradient.
o 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.
o 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.
o Implement the Adagrad method in order to tune the learning rate. Do this with and without momentum for plain gradient descent and SGD.
o Add RMSprop and Adam to your library of methods for tuning the learning rate.
The lecture notes from "weeks 39 and 40 contain more
details":"https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html" and code examples. Feel free to use these examples.
o Replace thereafter your analytical gradient with either _Autograd_ or _JAX_
===== Classification and Regression, writing our own neural network code =====
_Feel free to use codes on these methods from the lecture notes from week 39 and week 40_.
The main aim of this project is to study both classification and
regression problems by developing our own
feed-forward neural network (FFNN) code. The exercises from week 41 and 42 (see URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html" and URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html") as well as the lecture material from the same weeks (see URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html" and URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html") should contain enough information for you to get started with writing your own code.
We will also reuse our codes on gradient descent methods from project 1.
The data sets that we propose here are (the default sets)
* 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
o The simple one-dimensional function Runge function from project 1, that is $f(x) = \frac{1}{1+25x^2}$. We recommend using a simpler function when developing your neural network code for regression problems. You should however feel free to discuss and study other functions, such as the the two-dimensional Runge function $f(x,y)=\left[(10x - 5)^2 + (10y - 5)^2 + 1 \right]^{-1}$, or even more complicated two-dimensional functions (see the supplementary material of URL:"https://www.nature.com/articles/s41467-025-61362-4" for an extensive list of two-dimensional functions).
* Classification.
o We will consider the multiclass classification problem given by the full MNIST data set. The one included in _scikit-learn_ is reduced data. The full data set is at URL:"https://www.kaggle.com/datasets/hojjatk/mnist-dataset".
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 _Scikit-Learn_'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.
You will need your SGD code for the setup of the Neural Network and
Logistic Regression codes. You will find the Python "Seaborn
We will start with a regression problem and we will reuse our codes on gradient descent methods from project 1.
=== Part a): Analytical warm-up ===
When using our gradient machinery from project 1, we will need the expressions for the cost/loss functions and their respective
gradients. The functions whose gradients we need are:
o The mean-squared error (MSE) with and without the $L_1$ and $L_2$ norms (regression problems)
o The binary cross entropy (aka log loss) for classification problems with and without $L_1$ and $L_2$ norms
o The multiclass cross entropy cost/loss function (aka Softmax cross entropy or just Softmax loss function)
Set up these three cost/loss functions and their respective derivatives and explain the various terms.
We will test three activation functions for our neural network setup, these are the
o The Sigmoid (aka _logit_) function,
o the RELU function and
o the Leaky RELU function
Set up their expressions and their first derivatives.
You may consult the lecture notes (with codes and more) from week 42 at URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html".
=== Reminder about the gradient machinery from project 1 ===
In the setup of a neural network code you will need your gradient descent codes from
project 1. For neural networks we will recommend using stochastic
gradient descent with either the RMSprop or the ADAM algorithms for
updating the learning rates. But you should feel free to try plain gradient descent as well.
We recommend reading chapter 8 on optimization from the textbook of
Goodfellow, Bengio and Courville at
URL:"https://www.deeplearningbook.org/". This chapter contains many
useful insights and discussions on the optimization part of machine
learning. A useful reference on the back progagation algorithm is
Nielsen's book at URL:"http://neuralnetworksanddeeplearning.com/".
You will find the Python "Seaborn
package":"https://seaborn.pydata.org/generated/seaborn.heatmap.html"
useful when plotting the results as function of the learning rate
$\eta$ and the hyper-parameter $\lambda$ when you use Ridge
regression. Since you will use different gradient descent methods, you can also add Lasse regression. This is however optional. How to code Lasso regression is discussed in the lecture notes from week 40.
$\eta$ and the hyper-parameter $\lambda$ .
We recommend reading chapter 8 on optimization from the textbook of Goodfellow, Bengio and Courville at URL:"https://www.deeplearningbook.org/". This chapter contains many useful insights and discussions on the optimization part of machine learning.
=== Part b): Writing your own Neural Network code ===
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 "week 41":"https://compphysics.github.io/MachineLearning/doc/pub/week41/ipynb/week41.ipynb" and
"week 42":"https://compphysics.github.io/MachineLearning/doc/pub/week42/ipynb/week42.ipynb".
write your own FFNN code implementing the back
propagation algorithm discussed in the lecture slides from week 41 at URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html" and week 42 at URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html".
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.
Discuss again your choice of cost function.
We will focus on a regression problem first, using the one-dimensional Runge function
!bt
\[
f(x) = \frac{1}{1+25x^2},
\]
!et
from project 1.
Write an FFNN code for regression with a flexible number of hidden
layers and nodes using the Sigmoid function as activation function for
Use only the mean-squared error as cost function (no regularization terms) and
write an FFNN code for a regression problem with a flexible number of hidden
layers and nodes using only 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?
And how would you set up your design/feature matrix? Hint: does it have to represent a polynomial approximation as you did in project 1?
Train your network and compare the results with those from your OLS
regression code from project 1 using the one-dimensional Runge
function. When comparing your neural network code with the OLS
results from project 1, use the same data sets which gave you the best
MSE score. Moreover, use the polynomial order from project 1 that gave you the
best result. Compare these results with your neural network with one
and two hidden layers using $50$ and $100$ hidden nodes, respectively.
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 _Scikit-Learn_ (see the examples in the above lecture notes from weeks 41 and 42) or _tensorflow/keras_ or _Pytorch_ (for Pytorch, see Raschka et al.'s text chapters 12 and 13).
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.
obtained with the OLS code from project 1 and your own neural network
code. Make an analysis of the learning rates employed to find the
optimal MSE and $R2$ scores. Test both stochastic gradient descent
with RMSprop and ADAM and plain gradient descent with different
learning rates.
A useful reference on the back progagation algorithm is Nielsen's book at URL:"http://neuralnetworksanddeeplearning.com/". It is an excellent
read.
You should, as you did in project 1, scale your data.
=== Part c): Testing against other software libraries ===
You should test your results against a similar code using _Scikit-Learn_ (see the examples in the above lecture notes from weeks 41 and 42) or _tensorflow/keras_ or _Pytorch_ (for Pytorch, see Raschka et al.'s text chapters 12 and 13).
Furthermore, you should also test that your derivatives are correctly
calculated using automatic differentiation, using for example the
_Autograd_ library or the _JAX_ library. It is optional to implement
these libraries for the present project. In this project they serve as
useful tests of our derivatives.
=== Part d): Testing different activation functions and depths of the neural network ===
You should also test different activation functions for the hidden
layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and
discuss your results. Test your results as functions of the number of hidden layers and nodes. Do you see signs of overfitting?
It is optional in this project to perform a bias-variance trade-off analysis.
=== Part c): Testing different activation functions ===
=== Part e): Testing different norms ===
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.
=== Part d): Classification analysis using neural networks ===
Finally, still using the one-dimensional Runge function, add now the
hyperparameters $\lambda$ with the $L_2$ and $L_1$ norms. Find the
optimal results for the hyperparameters $\lambda$ and the learning
rates $\eta$ and neural network architecture and compare the $L_2$ results with Ridge regression from
project 1 and the $L_1$ results with the Lasso calculations of project 1.
Use again the same data sets and the best results from project 1 in your comparisons.
=== Part f): Classification analysis using neural networks ===
With a well-written code it should now be easy to change the
activation function for the output layer.
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.
developed in parts b), d) and e) in order to perform a classification
analysis. The classification problem we will study is the multiclass
MNIST problem, see the description of the full data set at
URL:"https://www.kaggle.com/datasets/hojjatk/mnist-dataset". We will use the Softmax cross entropy function discussed in a).
The MNIST data set discussed in the lecture notes from week 42 is a downscaled variant of the full dataset.
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 "Scikit-Learn
site":"https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html" or at the "University of California
at Irvine":"https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)".
Feel free to suggest other data sets. If you find the classic MNIST data set somewhat limited, feel free to try the
MNIST-Fashion data set at for example URL:"https://www.kaggle.com/datasets/zalando-research/fashionmnist".
To measure the performance of our classification problem we use the
To set up the data set, the following python programs may be useful
!bc pycod
from sklearn.datasets import fetch_openml
# Fetch the MNIST dataset
mnist = fetch_openml('mnist_784', version=1, as_frame=False, parser='auto')
# Extract data (features) and target (labels)
X = mnist.data
y = mnist.target
!ec
You should consider scaling the data. The Pixel values in MNIST range from 0 to 255. Scaling them to a 0-1 range can improve the performance of some models. That is, you could implement the following scaling
!bc pycod
X = X / 255.0
!ec
And then perform the standard train-test splitting
!bc pycod
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
!ec
To measure the performance of our classification problem we will use the
so-called *accuracy* 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
@@ -154,35 +251,32 @@ 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$.
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.
Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter $\lambda$, various activation functions, number of hidden layers and nodes and activation functions.
As stated in the introduction, it can also be useful to study other
datasets.
Again, we strongly recommend that you compare your own neural Network
code for classification and pertinent results against a similar code using _Scikit-Learn_ or _tensorflow/keras_ or _pytorch_.
If you have time, you can use the functionality of _scikit-learn_ and compare your neural network results with those from Logistic regression. This is optional.
The weblink here URL:"https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3"compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article. Your neural network code can implement the equivalent of logistic regression by simply setting the number of hidden layers to zero.
If you wish to compare with say Logisti Regression from _scikit-learn_, the following code uses the above data set
!bc pycod
from sklearn.linear_model import LogisticRegression
# Initialize the model
model = LogisticRegression(solver='saga', multi_class='multinomial', max_iter=1000, random_state=42)
# Train the model
model.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
# Make predictions on the test set
y_pred = model.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.4f}")
!ec
=== Part e): Write your Logistic Regression code, final step ===
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.
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 _Scikit-Learn_'s logistic regression functionality.
The weblink here URL:"https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3"compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article.
=== Part f) Critical evaluation of the various algorithms ===
=== Part g) Critical evaluation of the various algorithms ===
After all these glorious calculations, you should now summarize the
various algorithms and come with a critical evaluation of their pros
+1 -1
View File
@@ -51,7 +51,7 @@ mv -f $name.pdf ${name}.pdf
cp $name.tex ${name}.tex
# Publish
dest=../../../../Projects/2024
dest=../../../../Projects/2025
if [ ! -d $dest/$name ]; then
mkdir $dest/$name
mkdir $dest/$name/pdf