updating week 41

This commit is contained in:
Morten Hjorth-Jensen
2025-10-05 20:06:15 +02:00
parent c048076fef
commit 250a59fbbd
14 changed files with 5544 additions and 5290 deletions
File diff suppressed because it is too large Load Diff
+44 -751
View File
@@ -177,7 +177,7 @@ MathJax.Hub.Config({
</center>
<!-- institution -->
<center>
<b>Department of Physics, University of Oslo</b>
<b>Department of Physics, University of Oslo, Norway</b>
</center>
<br>
<center>
@@ -187,26 +187,21 @@ MathJax.Hub.Config({
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
<!-- copyright --> &copy; 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</section>
<section>
<h2 id="plan-for-week-41-october-7-11">Plan for week 41, October 7-11 </h2>
<h2 id="plan-for-week-41-october-6-10">Plan for week 41, October 6-10 </h2>
</section>
<section>
<h2 id="material-for-the-lecture-on-monday-october-7-2024">Material for the lecture on Monday October 7, 2024 </h2>
<h2 id="material-for-the-lecture-on-monday-october-6-2025">Material for the lecture on Monday October 6, 2025 </h2>
<ol>
<p><li> Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.</li>
<p><li> Building our own Feed-forward Neural Network</li>
<ul>
<p><li> Video of lecture notes at <a href="https://youtu.be/pMRUbf9E-gM" target="_blank"><tt>https://youtu.be/pMRUbf9E-gM</tt></a></li>
<p><li> Whiteboard notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf</tt></a></li>
</ul>
<p>
<p><li> Building our own Feed-forward Neural Network, getting started
<!-- * Video of lecture notes at <a href="https://youtu.be/pMRUbf9E-gM" target="_blank"><tt>https://youtu.be/pMRUbf9E-gM</tt></a> -->
<!-- * Whiteboard notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf</tt></a> --></li>
</ol>
<p>
<div class="alert alert-block alert-block alert-text-normal">
@@ -214,10 +209,10 @@ MathJax.Hub.Config({
<p>
<ol>
<p><li> These lecture notes</li>
<p><li> Rashcka et al chapter 11</li>
<p><li> For neural networks we recommend Goodfellow et al chapter 6.
<p><li> For neural networks we recommend Goodfellow et al chapters 6 and 7.</li>
<p><li> Rashkca et al., chapter 11, jupyter-notebook sent separately, from <a href="https://github.com/rasbt/machine-learning-book" target="_blank">GitHub</a>
<ol type="a"></li>
<p><li> Neural Networks demystified at <a href="https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" target="_blank"><tt>https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs</tt></a></li>
<p><li> Neural Networks demystified at <a href="https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" target="_blank"><tt>https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs</tt></a></li>
</ol>
<p>
<p><li> Building Neural Networks from scratch at <a href="https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex" target="_blank"><tt>https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex</tt></a></li>
@@ -230,17 +225,39 @@ MathJax.Hub.Config({
</section>
<section>
<h2 id="material-for-the-active-learning-sessions-on-tuesday-and-wednesday">Material for the active learning sessions on Tuesday and Wednesday </h2>
<ul>
<p><li> Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation</li>
<p><li> One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code</li>
<p><li> Discussion of project 2</li>
<p><li> Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent</li>
</ul>
<h2 id="mathematics-of-deep-learning">Mathematics of deep learning </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Two recent books online</b>
<p>
<ol>
<p><li> <a href="https://arxiv.org/abs/2105.04026" target="_blank">The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen</a>, published as <a href="https://doi.org/10.1017/9781009025096.002" target="_blank">Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022</a></li>
<p><li> <a href="https://doi.org/10.48550/arXiv.2310.20360" target="_blank">Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger</a></li>
</ol>
</div>
</section>
<section>
<h2 id="lecture-monday-october-7">Lecture Monday October 7 </h2>
<h2 id="reminder-on-books-with-hands-on-material-and-codes">Reminder on books with hands-on material and codes </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ul>
<p><li> <a href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" target="_blank">Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch</a></li>
</ul>
</div>
</section>
<section>
<h2 id="lab-sessions-on-tuesday-and-wednesday">Lab sessions on Tuesday and Wednesday </h2>
<ol>
<p><li> Getting started with coding neural network. The exercises this week aim at setting up the feed-forward part of a neural network.</li>
</ol>
</section>
<section>
<h2 id="lecture-monday-october-6">Lecture Monday October 6 </h2>
</section>
<section>
@@ -461,215 +478,6 @@ as to not restrict the range of output values.
</center>
</section>
<section>
<h2 id="examples-of-xor-or-and-and-gates">Examples of XOR, OR and AND gates </h2>
<p>Let us first try to fit various gates using standard linear
regression. The gates we are thinking of are the classical XOR, OR and
AND gates, well-known elements in computer science. The tables here
show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a
specific target \( y_i \).
</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #CD5555">&quot;&quot;&quot;</span>
<span style="color: #CD5555">Simple code that tests XOR, OR and AND gates with linear regression</span>
<span style="color: #CD5555">&quot;&quot;&quot;</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #228B22"># Design matrix</span>
X = np.array([ [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>, <span style="color: #B452CD">0</span>], [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>], [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>],[<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>]],dtype=np.float64)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The X.TX matrix:{</span>X.T @ X<span style="color: #CD5555">}&quot;</span>)
Xinv = np.linalg.pinv(X.T @ X)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The invers of X.TX matrix:{</span>Xinv<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The XOR gate </span>
yXOR = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span> ,<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>])
ThetaXOR = Xinv @ X.T @ yXOR
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the XOR gate:{</span>ThetaXOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the XOR gate:{</span>X @ ThetaXOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The OR gate </span>
yOR = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span> ,<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>])
ThetaOR = Xinv @ X.T @ yOR
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the OR gate:{</span>ThetaOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the OR gate:{</span>X @ ThetaOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The OR gate </span>
yAND = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">0</span> ,<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>])
ThetaAND = Xinv @ X.T @ yAND
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the AND gate:{</span>ThetaAND<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the AND gate:{</span>X @ ThetaAND<span style="color: #CD5555">}&quot;</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>What is happening here?</p>
</section>
<section>
<h2 id="does-logistic-regression-do-a-better-job">Does Logistic Regression do a better Job? </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #CD5555">&quot;&quot;&quot;</span>
<span style="color: #CD5555">Simple code that tests XOR and OR gates with linear regression</span>
<span style="color: #CD5555">and logistic regression</span>
<span style="color: #CD5555">&quot;&quot;&quot;</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.linear_model</span> <span style="color: #8B008B; font-weight: bold">import</span> LogisticRegression
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #228B22"># Design matrix</span>
X = np.array([ [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>, <span style="color: #B452CD">0</span>], [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>], [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>],[<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>]],dtype=np.float64)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The X.TX matrix:{</span>X.T @ X<span style="color: #CD5555">}&quot;</span>)
Xinv = np.linalg.pinv(X.T @ X)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The invers of X.TX matrix:{</span>Xinv<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The XOR gate </span>
yXOR = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span> ,<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>])
ThetaXOR = Xinv @ X.T @ yXOR
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the XOR gate:{</span>ThetaXOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the XOR gate:{</span>X @ ThetaXOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The OR gate </span>
yOR = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span> ,<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>])
ThetaOR = Xinv @ X.T @ yOR
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the OR gate:{</span>ThetaOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the OR gate:{</span>X @ ThetaOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The OR gate </span>
yAND = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">0</span> ,<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>])
ThetaAND = Xinv @ X.T @ yAND
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the AND gate:{</span>ThetaAND<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the AND gate:{</span>X @ ThetaAND<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># Now we change to logistic regression</span>
<span style="color: #228B22"># Logistic Regression</span>
logreg = LogisticRegression()
logreg.fit(X, yOR)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy with Logistic Regression for OR gate: {:.2f}&quot;</span>.format(logreg.score(X,yOR)))
logreg.fit(X, yXOR)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy with Logistic Regression for XOR gate: {:.2f}&quot;</span>.format(logreg.score(X,yXOR)))
logreg.fit(X, yAND)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy with Logistic Regression for AND gate: {:.2f}&quot;</span>.format(logreg.score(X,yAND)))
</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>Not exactly impressive, but somewhat better.</p>
</section>
<section>
<h2 id="adding-neural-networks">Adding Neural Networks </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #228B22"># and now neural networks with Scikit-Learn and the XOR</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.neural_network</span> <span style="color: #8B008B; font-weight: bold">import</span> MLPClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.datasets</span> <span style="color: #8B008B; font-weight: bold">import</span> make_classification
X, yXOR = make_classification(n_samples=<span style="color: #B452CD">100</span>, random_state=<span style="color: #B452CD">1</span>)
FFNN = MLPClassifier(random_state=<span style="color: #B452CD">1</span>, max_iter=<span style="color: #B452CD">300</span>).fit(X, yXOR)
FFNN.predict_proba(X)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;Test set accuracy with Feed Forward Neural Network for XOR gate:{</span>FFNN.score(X, yXOR)<span style="color: #CD5555">}&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>
</section>
<section>
<h2 id="mathematics-of-deep-learning">Mathematics of deep learning </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Two recent books online</b>
<p>
<ol>
<p><li> <a href="https://arxiv.org/abs/2105.04026" target="_blank">The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen</a>, published as <a href="https://doi.org/10.1017/9781009025096.002" target="_blank">Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022</a></li>
<p><li> <a href="https://doi.org/10.48550/arXiv.2310.20360" target="_blank">Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger</a></li>
</ol>
</div>
</section>
<section>
<h2 id="reminder-on-books-with-hands-on-material-and-codes">Reminder on books with hands-on material and codes </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ul>
<p><li> <a href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" target="_blank">Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch</a></li>
</ul>
</div>
</section>
<section>
<h2 id="reading-recommendations">Reading recommendations </h2>
<ol>
<p><li> Rashkca et al., chapter 11, jupyter-notebook sent separately, from <a href="https://github.com/rasbt/machine-learning-book" target="_blank">GitHub</a></li>
<p><li> Goodfellow et al, chapter 6 and 7 contain most of the neural network background.</li>
</ol>
</section>
<section>
<h2 id="mathematics-of-deep-learning-and-neural-networks">Mathematics of deep learning and neural networks </h2>
@@ -1030,7 +838,7 @@ $$
<p>In order to understand the back propagation algorithm and its
derivation (an implementation of the chain rule), let us first digress
with some simple examples. These examples are also meant to motivate
the link with back propagation and <a href="https://en.wikipedia.org/wiki/Automatic_differentiation" target="_blank">automatic differentiation</a>.
the link with back propagation and <a href="https://en.wikipedia.org/wiki/Automatic_differentiation" target="_blank">automatic differentiation</a>. We will discuss these topics next week (week 42).
</p>
</section>
@@ -1073,7 +881,9 @@ $$
<section>
<h2 id="automatic-differentiation-through-examples">Automatic differentiation through examples </h2>
<p>A great introduction to automatic differentiation is given by Baydin et al., see <a href="https://arxiv.org/abs/1502.05767" target="_blank"><tt>https://arxiv.org/abs/1502.05767</tt></a>.</p>
<p>A great introduction to automatic differentiation is given by Baydin et al., see <a href="https://arxiv.org/abs/1502.05767" target="_blank"><tt>https://arxiv.org/abs/1502.05767</tt></a>.
See also the video at <a href="https://www.youtube.com/watch?v=wG_nF1awSSY" target="_blank"><tt>https://www.youtube.com/watch?v=wG_nF1awSSY</tt></a>.
</p>
<p>Automatic differentiation is a represented by a repeated application
of the chain rule on well-known functions and allows for the
@@ -2329,523 +2139,6 @@ $$
<p>&nbsp;<br>
</section>
<section>
<h3 id="activation-functions">Activation functions </h3>
<p>A property that characterizes a neural network, other than its
connectivity, is the choice of activation function(s). As described
in, the following restrictions are imposed on an activation function
for a FFNN to fulfill the universal approximation theorem
</p>
<ul>
<p><li> Non-constant</li>
<p><li> Bounded</li>
<p><li> Monotonically-increasing</li>
<p><li> Continuous</li>
</ul>
</section>
<section>
<h3 id="activation-functions-logistic-and-hyperbolic-ones">Activation functions, Logistic and Hyperbolic ones </h3>
<p>The second requirement excludes all linear functions. Furthermore, in
a MLP with only linear activation functions, each layer simply
performs a linear transformation of its inputs.
</p>
<p>Regardless of the number of layers, the output of the NN will be
nothing but a linear function of the inputs. Thus we need to introduce
some kind of non-linearity to the NN to be able to fit non-linear
functions Typical examples are the logistic <em>Sigmoid</em>
</p>
<p>&nbsp;<br>
$$
f(x) = \frac{1}{1 + e^{-x}},
$$
<p>&nbsp;<br>
<p>and the <em>hyperbolic tangent</em> function</p>
<p>&nbsp;<br>
$$
f(x) = \tanh(x)
$$
<p>&nbsp;<br>
</section>
<section>
<h3 id="relevance">Relevance </h3>
<p>The <em>sigmoid</em> function are more biologically plausible because the
output of inactive neurons are zero. Such activation function are
called <em>one-sided</em>. However, it has been shown that the hyperbolic
tangent performs better than the sigmoid for training MLPs. has
become the most popular for <em>deep neural networks</em>
</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #CD5555">&quot;&quot;&quot;The sigmoid function (or the logistic curve) is a </span>
<span style="color: #CD5555">function that takes any real number, z, and outputs a number (0,1).</span>
<span style="color: #CD5555">It is useful in neural networks for assigning weights on a relative scale.</span>
<span style="color: #CD5555">The value z is the weighted sum of parameters involved in the learning algorithm.&quot;&quot;&quot;</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">math</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">mt</span>
z = numpy.arange(-<span style="color: #B452CD">5</span>, <span style="color: #B452CD">5</span>, <span style="color: #B452CD">.1</span>)
sigma_fn = numpy.vectorize(<span style="color: #8B008B; font-weight: bold">lambda</span> z: <span style="color: #B452CD">1</span>/(<span style="color: #B452CD">1</span>+numpy.exp(-z)))
sigma = sigma_fn(z)
fig = plt.figure()
ax = fig.add_subplot(<span style="color: #B452CD">111</span>)
ax.plot(z, sigma)
ax.set_ylim([-<span style="color: #B452CD">0.1</span>, <span style="color: #B452CD">1.1</span>])
ax.set_xlim([-<span style="color: #B452CD">5</span>,<span style="color: #B452CD">5</span>])
ax.grid(<span style="color: #8B008B; font-weight: bold">True</span>)
ax.set_xlabel(<span style="color: #CD5555">&#39;z&#39;</span>)
ax.set_title(<span style="color: #CD5555">&#39;sigmoid function&#39;</span>)
plt.show()
<span style="color: #CD5555">&quot;&quot;&quot;Step Function&quot;&quot;&quot;</span>
z = numpy.arange(-<span style="color: #B452CD">5</span>, <span style="color: #B452CD">5</span>, <span style="color: #B452CD">.02</span>)
step_fn = numpy.vectorize(<span style="color: #8B008B; font-weight: bold">lambda</span> z: <span style="color: #B452CD">1.0</span> <span style="color: #8B008B; font-weight: bold">if</span> z &gt;= <span style="color: #B452CD">0.0</span> <span style="color: #8B008B; font-weight: bold">else</span> <span style="color: #B452CD">0.0</span>)
step = step_fn(z)
fig = plt.figure()
ax = fig.add_subplot(<span style="color: #B452CD">111</span>)
ax.plot(z, step)
ax.set_ylim([-<span style="color: #B452CD">0.5</span>, <span style="color: #B452CD">1.5</span>])
ax.set_xlim([-<span style="color: #B452CD">5</span>,<span style="color: #B452CD">5</span>])
ax.grid(<span style="color: #8B008B; font-weight: bold">True</span>)
ax.set_xlabel(<span style="color: #CD5555">&#39;z&#39;</span>)
ax.set_title(<span style="color: #CD5555">&#39;step function&#39;</span>)
plt.show()
<span style="color: #CD5555">&quot;&quot;&quot;Sine Function&quot;&quot;&quot;</span>
z = numpy.arange(-<span style="color: #B452CD">2</span>*mt.pi, <span style="color: #B452CD">2</span>*mt.pi, <span style="color: #B452CD">0.1</span>)
t = numpy.sin(z)
fig = plt.figure()
ax = fig.add_subplot(<span style="color: #B452CD">111</span>)
ax.plot(z, t)
ax.set_ylim([-<span style="color: #B452CD">1.0</span>, <span style="color: #B452CD">1.0</span>])
ax.set_xlim([-<span style="color: #B452CD">2</span>*mt.pi,<span style="color: #B452CD">2</span>*mt.pi])
ax.grid(<span style="color: #8B008B; font-weight: bold">True</span>)
ax.set_xlabel(<span style="color: #CD5555">&#39;z&#39;</span>)
ax.set_title(<span style="color: #CD5555">&#39;sine function&#39;</span>)
plt.show()
<span style="color: #CD5555">&quot;&quot;&quot;Plots a graph of the squashing function used by a rectified linear</span>
<span style="color: #CD5555">unit&quot;&quot;&quot;</span>
z = numpy.arange(-<span style="color: #B452CD">2</span>, <span style="color: #B452CD">2</span>, <span style="color: #B452CD">.1</span>)
zero = numpy.zeros(<span style="color: #658b00">len</span>(z))
y = numpy.max([zero, z], axis=<span style="color: #B452CD">0</span>)
fig = plt.figure()
ax = fig.add_subplot(<span style="color: #B452CD">111</span>)
ax.plot(z, y)
ax.set_ylim([-<span style="color: #B452CD">2.0</span>, <span style="color: #B452CD">2.0</span>])
ax.set_xlim([-<span style="color: #B452CD">2.0</span>, <span style="color: #B452CD">2.0</span>])
ax.grid(<span style="color: #8B008B; font-weight: bold">True</span>)
ax.set_xlabel(<span style="color: #CD5555">&#39;z&#39;</span>)
ax.set_title(<span style="color: #CD5555">&#39;Rectified linear unit&#39;</span>)
plt.show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
</section>
<section>
<h2 id="fine-tuning-neural-network-hyperparameters">Fine-tuning neural network hyperparameters </h2>
<p>The flexibility of neural networks is also one of their main
drawbacks: there are many hyperparameters to tweak. Not only can you
use any imaginable network topology (how neurons/nodes are
interconnected), but even in a simple FFNN you can change the number
of layers, the number of neurons per layer, the type of activation
function to use in each layer, the weight initialization logic, the
stochastic gradient optmized and much more. How do you know what
combination of hyperparameters is the best for your task?
</p>
<ul>
<p><li> You can use grid search with cross-validation to find the right hyperparameters.</li>
</ul>
<p>
<p>However,since there are many hyperparameters to tune, and since
training a neural network on a large dataset takes a lot of time, you
will only be able to explore a tiny part of the hyperparameter space.
</p>
<ul>
<p><li> You can use randomized search.</li>
<p><li> Or use tools like <a href="http://oscar.calldesk.ai/" target="_blank">Oscar</a>, which implements more complex algorithms to help you find a good set of hyperparameters quickly.</li>
</ul>
</section>
<section>
<h2 id="hidden-layers">Hidden layers </h2>
<p>For many problems you can start with just one or two hidden layers and
it will work just fine. For the MNIST data set you ca easily get a
high accuracy using just one hidden layer with a few hundred neurons.
You can reach for this data set above 98% accuracy using two hidden
layers with the same total amount of neurons, in roughly the same
amount of training time.
</p>
<p>For more complex problems, you can gradually ramp up the number of
hidden layers, until you start overfitting the training set. Very
complex tasks, such as large image classification or speech
recognition, typically require networks with dozens of layers and they
need a huge amount of training data. However, you will rarely have to
train such networks from scratch: it is much more common to reuse
parts of a pretrained state-of-the-art network that performs a similar
task.
</p>
</section>
<section>
<h2 id="vanishing-gradients">Vanishing gradients </h2>
<p>The Back propagation algorithm we derived above works by going from
the output layer to the input layer, propagating the error gradient on
the way. Once the algorithm has computed the gradient of the cost
function with regards to each parameter in the network, it uses these
gradients to update each parameter with a Gradient Descent (GD) step.
</p>
<p>Unfortunately for us, the gradients often get smaller and smaller as
the algorithm progresses down to the first hidden layers. As a result,
the GD update leaves the lower layer connection weights virtually
unchanged, and training never converges to a good solution. This is
known in the literature as <b>the vanishing gradients problem</b>.
</p>
</section>
<section>
<h2 id="exploding-gradients">Exploding gradients </h2>
<p>In other cases, the opposite can happen, namely the the gradients can
grow bigger and bigger. The result is that many of the layers get
large updates of the weights the algorithm diverges. This is the
<b>exploding gradients problem</b>, which is mostly encountered in
recurrent neural networks. More generally, deep neural networks suffer
from unstable gradients, different layers may learn at widely
different speeds
</p>
</section>
<section>
<h2 id="is-the-logistic-activation-function-sigmoid-our-choice">Is the Logistic activation function (Sigmoid) our choice? </h2>
<p>Although this unfortunate behavior has been empirically observed for
quite a while (it was one of the reasons why deep neural networks were
mostly abandoned for a long time), it is only around 2010 that
significant progress was made in understanding it.
</p>
<p>A paper titled <a href="http://proceedings.mlr.press/v9/glorot10a.html" target="_blank">Understanding the Difficulty of Training Deep
Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio</a> found that
the problems with the popular logistic
sigmoid activation function and the weight initialization technique
that was most popular at the time, namely random initialization using
a normal distribution with a mean of 0 and a standard deviation of
1.
</p>
</section>
<section>
<h2 id="logistic-function-as-the-root-of-problems">Logistic function as the root of problems </h2>
<p>They showed that with this activation function and this
initialization scheme, the variance of the outputs of each layer is
much greater than the variance of its inputs. Going forward in the
network, the variance keeps increasing after each layer until the
activation function saturates at the top layers. This is actually made
worse by the fact that the logistic function has a mean of 0.5, not 0
(the hyperbolic tangent function has a mean of 0 and behaves slightly
better than the logistic function in deep networks).
</p>
</section>
<section>
<h2 id="the-derivative-of-the-logistic-funtion">The derivative of the Logistic funtion </h2>
<p>Looking at the logistic activation function, when inputs become large
(negative or positive), the function saturates at 0 or 1, with a
derivative extremely close to 0. Thus when backpropagation kicks in,
it has virtually no gradient to propagate back through the network,
and what little gradient exists keeps getting diluted as
backpropagation progresses down through the top layers, so there is
really nothing left for the lower layers.
</p>
<p>In their paper, Glorot and Bengio propose a way to significantly
alleviate this problem. We need the signal to flow properly in both
directions: in the forward direction when making predictions, and in
the reverse direction when backpropagating gradients. We don&#8217;t want
the signal to die out, nor do we want it to explode and saturate. For
the signal to flow properly, the authors argue that we need the
variance of the outputs of each layer to be equal to the variance of
its inputs, and we also need the gradients to have equal variance
before and after flowing through a layer in the reverse direction.
</p>
</section>
<section>
<h2 id="insights-from-the-paper-by-glorot-and-bengio">Insights from the paper by Glorot and Bengio </h2>
<p>One of the insights in the 2010 paper by Glorot and Bengio was that
the vanishing/exploding gradients problems were in part due to a poor
choice of activation function. Until then most people had assumed that
if Nature had chosen to use roughly sigmoid activation functions in
biological neurons, they must be an excellent choice. But it turns out
that other activation functions behave much better in deep neural
networks, in particular the ReLU activation function, mostly because
it does not saturate for positive values (and also because it is quite
fast to compute).
</p>
</section>
<section>
<h2 id="the-relu-function-family">The RELU function family </h2>
<p>The ReLU activation function suffers from a problem known as the dying
ReLUs: during training, some neurons effectively die, meaning they
stop outputting anything other than 0.
</p>
<p>In some cases, you may find that half of your network&#8217;s neurons are
dead, especially if you used a large learning rate. During training,
if a neuron&#8217;s weights get updated such that the weighted sum of the
neuron&#8217;s inputs is negative, it will start outputting 0. When this
happen, the neuron is unlikely to come back to life since the gradient
of the ReLU function is 0 when its input is negative.
</p>
</section>
<section>
<h2 id="elu-function">ELU function </h2>
<p>To solve this problem, nowadays practitioners use a variant of the
ReLU function, such as the leaky ReLU discussed above or the so-called
exponential linear unit (ELU) function
</p>
<p>&nbsp;<br>
$$
ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right.
$$
<p>&nbsp;<br>
</section>
<section>
<h2 id="which-activation-function-should-we-use">Which activation function should we use? </h2>
<p>In general it seems that the ELU activation function is better than
the leaky ReLU function (and its variants), which is better than
ReLU. ReLU performs better than \( \tanh \) which in turn performs better
than the logistic function.
</p>
<p>If runtime performance is an issue, then you may opt for the leaky
ReLU function over the ELU function If you don&#8217;t want to tweak yet
another hyperparameter, you may just use the default \( \alpha \) of
\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and
computing power, you can use cross-validation or bootstrap to evaluate
other activation functions.
</p>
</section>
<section>
<h2 id="more-on-activation-functions-output-layers">More on activation functions, output layers </h2>
<p>In most cases you can use the ReLU activation function in the hidden
layers (or one of its variants).
</p>
<p>It is a bit faster to compute than other activation functions, and the
gradient descent optimization does in general not get stuck.
</p>
<b>For the output layer:</b>
<ul>
<p><li> For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).</li>
<p><li> For regression tasks, you can simply use no activation function at all.</li>
</ul>
</section>
<section>
<h2 id="batch-normalization">Batch Normalization </h2>
<p>Batch Normalization aims to address the vanishing/exploding gradients
problems, and more generally the problem that the distribution of each
layer&#8217;s inputs changes during training, as the parameters of the
previous layers change.
</p>
<p>The technique consists of adding an operation in the model just before
the activation function of each layer, simply zero-centering and
normalizing the inputs, then scaling and shifting the result using two
new parameters per layer (one for scaling, the other for shifting). In
other words, this operation lets the model learn the optimal scale and
mean of the inputs for each layer. In order to zero-center and
normalize the inputs, the algorithm needs to estimate the inputs&#8217; mean
and standard deviation. It does so by evaluating the mean and standard
deviation of the inputs over the current mini-batch, from this the
name batch normalization.
</p>
</section>
<section>
<h2 id="dropout">Dropout </h2>
<p>It is a fairly simple algorithm: at every training step, every neuron
(including the input neurons but excluding the output neurons) has a
probability \( p \) of being temporarily dropped out, meaning it will be
entirely ignored during this training step, but it may be active
during the next step.
</p>
<p>The hyperparameter \( p \) is called the dropout rate, and it is typically
set to 50%. After training, the neurons are not dropped anymore. It
is viewed as one of the most popular regularization techniques.
</p>
</section>
<section>
<h2 id="gradient-clipping">Gradient Clipping </h2>
<p>A popular technique to lessen the exploding gradients problem is to
simply clip the gradients during backpropagation so that they never
exceed some threshold (this is mostly useful for recurrent neural
networks).
</p>
<p>This technique is called Gradient Clipping.</p>
<p>In general however, Batch
Normalization is preferred.
</p>
</section>
<section>
<h2 id="a-top-down-perspective-on-neural-networks">A top-down perspective on Neural networks </h2>
<p>The first thing we would like to do is divide the data into two or
three parts. A training set, a validation or dev (development) set,
and a test set. The test set is the data on which we want to make
predictions. The dev set is a subset of the training data we use to
check how well we are doing out-of-sample, after training the model on
the training dataset. We use the validation error as a proxy for the
test error in order to make tweaks to our model. It is crucial that we
do not use any of the test data to train the algorithm. This is a
cardinal sin in ML. Then:
</p>
<ol>
<p><li> Estimate optimal error rate</li>
<p><li> Minimize underfitting (bias) on training data set.</li>
<p><li> Make sure you are not overfitting.</li>
</ol>
</section>
<section>
<h2 id="more-top-down-perspectives">More top-down perspectives </h2>
<p>If the validation and test sets are drawn from the same distributions,
then a good performance on the validation set should lead to similarly
good performance on the test set.
</p>
<p>However, sometimes
the training data and test data differ in subtle ways because, for
example, they are collected using slightly different methods, or
because it is cheaper to collect data in one way versus another. In
this case, there can be a mismatch between the training and test
data. This can lead to the neural network overfitting these small
differences between the test and training sets, and a poor performance
on the test set despite having a good performance on the validation
set. To rectify this, Andrew Ng suggests making two validation or dev
sets, one constructed from the training data and one constructed from
the test data. The difference between the performance of the algorithm
on these two validation sets quantifies the train-test mismatch. This
can serve as another important diagnostic when using DNNs for
supervised learning.
</p>
</section>
<section>
<h2 id="limitations-of-supervised-learning-with-deep-networks">Limitations of supervised learning with deep networks </h2>
<p>Like all statistical methods, supervised learning using neural
networks has important limitations. This is especially important when
one seeks to apply these methods, especially to physics problems. Like
all tools, DNNs are not a universal solution. Often, the same or
better performance on a task can be achieved by using a few
hand-engineered features (or even a collection of random
features).
</p>
</section>
<section>
<h2 id="limitations-of-nns">Limitations of NNs </h2>
<p>Here we list some of the important limitations of supervised neural network based models. </p>
<ul>
<p><li> <b>Need labeled data</b>. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).</li>
<p><li> <b>Supervised neural networks are extremely data intensive.</b> DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.</li>
</ul>
</section>
<section>
<h2 id="homogeneous-data">Homogeneous data </h2>
<ul>
<p><li> <b>Homogeneous data.</b> Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e.&nbsp;some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.</li>
</ul>
</section>
<section>
<h2 id="more-limitations">More limitations </h2>
<ul>
<p><li> <b>Many problems are not about prediction.</b> In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a <em>wrong</em> model. The model might or might not be useful for understanding the underlying science.</li>
</ul>
<p>
<p>Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.</p>
</section>
</div> <!-- class="slides" -->
+61 -790
View File
@@ -63,23 +63,30 @@ div.toc p,a {
<!-- tocinfo
{'highest level': 2,
'sections': [('Plan for week 41, October 7-11',
'sections': [('Plan for week 41, October 6-10',
2,
None,
'plan-for-week-41-october-7-11'),
('Material for the lecture on Monday October 7, 2024',
'plan-for-week-41-october-6-10'),
('Material for the lecture on Monday October 6, 2025',
2,
None,
'material-for-the-lecture-on-monday-october-7-2024'),
('Material for the active learning sessions on Tuesday and '
'Wednesday',
'material-for-the-lecture-on-monday-october-6-2025'),
('Mathematics of deep learning',
2,
None,
'material-for-the-active-learning-sessions-on-tuesday-and-wednesday'),
('Lecture Monday October 7',
'mathematics-of-deep-learning'),
('Reminder on books with hands-on material and codes',
2,
None,
'lecture-monday-october-7'),
'reminder-on-books-with-hands-on-material-and-codes'),
('Lab sessions on Tuesday and Wednesday',
2,
None,
'lab-sessions-on-tuesday-and-wednesday'),
('Lecture Monday October 6',
2,
None,
'lecture-monday-october-6'),
('Introduction to Neural networks',
2,
None,
@@ -109,24 +116,6 @@ div.toc p,a {
2,
None,
'illustration-of-a-single-perceptron-model-and-a-multi-perceptron-model'),
('Examples of XOR, OR and AND gates',
2,
None,
'examples-of-xor-or-and-and-gates'),
('Does Logistic Regression do a better Job?',
2,
None,
'does-logistic-regression-do-a-better-job'),
('Adding Neural Networks', 2, None, 'adding-neural-networks'),
('Mathematics of deep learning',
2,
None,
'mathematics-of-deep-learning'),
('Reminder on books with hands-on material and codes',
2,
None,
'reminder-on-books-with-hands-on-material-and-codes'),
('Reading recommendations', 2, None, 'reading-recommendations'),
('Mathematics of deep learning and neural networks',
2,
None,
@@ -331,64 +320,7 @@ div.toc p,a {
2,
None,
'setting-up-the-back-propagation-algorithm-part-3'),
('Updating the gradients', 2, None, 'updating-the-gradients'),
('Activation functions', 3, None, 'activation-functions'),
('Activation functions, Logistic and Hyperbolic ones',
3,
None,
'activation-functions-logistic-and-hyperbolic-ones'),
('Relevance', 3, None, 'relevance'),
('Fine-tuning neural network hyperparameters',
2,
None,
'fine-tuning-neural-network-hyperparameters'),
('Hidden layers', 2, None, 'hidden-layers'),
('Vanishing gradients', 2, None, 'vanishing-gradients'),
('Exploding gradients', 2, None, 'exploding-gradients'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
'is-the-logistic-activation-function-sigmoid-our-choice'),
('Logistic function as the root of problems',
2,
None,
'logistic-function-as-the-root-of-problems'),
('The derivative of the Logistic funtion',
2,
None,
'the-derivative-of-the-logistic-funtion'),
('Insights from the paper by Glorot and Bengio',
2,
None,
'insights-from-the-paper-by-glorot-and-bengio'),
('The RELU function family', 2, None, 'the-relu-function-family'),
('ELU function', 2, None, 'elu-function'),
('Which activation function should we use?',
2,
None,
'which-activation-function-should-we-use'),
('More on activation functions, output layers',
2,
None,
'more-on-activation-functions-output-layers'),
('Batch Normalization', 2, None, 'batch-normalization'),
('Dropout', 2, None, 'dropout'),
('Gradient Clipping', 2, None, 'gradient-clipping'),
('A top-down perspective on Neural networks',
2,
None,
'a-top-down-perspective-on-neural-networks'),
('More top-down perspectives',
2,
None,
'more-top-down-perspectives'),
('Limitations of supervised learning with deep networks',
2,
None,
'limitations-of-supervised-learning-with-deep-networks'),
('Limitations of NNs', 2, None, 'limitations-of-nns'),
('Homogeneous data', 2, None, 'homogeneous-data'),
('More limitations', 2, None, 'more-limitations')]}
('Updating the gradients', 2, None, 'updating-the-gradients')]}
end of tocinfo -->
<body>
@@ -419,7 +351,7 @@ MathJax.Hub.Config({
</center>
<!-- institution -->
<center>
<b>Department of Physics, University of Oslo</b>
<b>Department of Physics, University of Oslo, Norway</b>
</center>
<br>
<center>
@@ -428,27 +360,25 @@ MathJax.Hub.Config({
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plan-for-week-41-october-7-11">Plan for week 41, October 7-11 </h2>
<h2 id="plan-for-week-41-october-6-10">Plan for week 41, October 6-10 </h2>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="material-for-the-lecture-on-monday-october-7-2024">Material for the lecture on Monday October 7, 2024 </h2>
<h2 id="material-for-the-lecture-on-monday-october-6-2025">Material for the lecture on Monday October 6, 2025 </h2>
<ol>
<li> Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.</li>
<li> Building our own Feed-forward Neural Network</li>
<ul>
<li> Video of lecture notes at <a href="https://youtu.be/pMRUbf9E-gM" target="_blank"><tt>https://youtu.be/pMRUbf9E-gM</tt></a></li>
<li> Whiteboard notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf</tt></a></li>
</ul>
<li> Building our own Feed-forward Neural Network, getting started
<!-- * Video of lecture notes at <a href="https://youtu.be/pMRUbf9E-gM" target="_blank"><tt>https://youtu.be/pMRUbf9E-gM</tt></a> -->
<!-- * Whiteboard notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf</tt></a> --></li>
</ol>
<div class="alert alert-block alert-block alert-text-normal">
<b>Readings and Videos:</b>
<p>
<ol>
<li> These lecture notes</li>
<li> Rashcka et al chapter 11</li>
<li> For neural networks we recommend Goodfellow et al chapter 6.
<li> For neural networks we recommend Goodfellow et al chapters 6 and 7.</li>
<li> Rashkca et al., chapter 11, jupyter-notebook sent separately, from <a href="https://github.com/rasbt/machine-learning-book" target="_blank">GitHub</a>
<ol type="a"></li>
<li> Neural Networks demystified at <a href="https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" target="_blank"><tt>https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs</tt></a></li>
<li> Neural Networks demystified at <a href="https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" target="_blank"><tt>https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs</tt></a></li>
</ol>
<li> Building Neural Networks from scratch at <a href="https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex" target="_blank"><tt>https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex</tt></a></li>
<li> Video on Neural Networks at <a href="https://www.youtube.com/watch?v=CqOfi41LfDw" target="_blank"><tt>https://www.youtube.com/watch?v=CqOfi41LfDw</tt></a></li>
@@ -459,15 +389,37 @@ MathJax.Hub.Config({
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="material-for-the-active-learning-sessions-on-tuesday-and-wednesday">Material for the active learning sessions on Tuesday and Wednesday </h2>
<ul>
<li> Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation</li>
<li> One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code</li>
<li> Discussion of project 2</li>
<li> Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent</li>
</ul>
<h2 id="mathematics-of-deep-learning">Mathematics of deep learning </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Two recent books online</b>
<p>
<ol>
<li> <a href="https://arxiv.org/abs/2105.04026" target="_blank">The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen</a>, published as <a href="https://doi.org/10.1017/9781009025096.002" target="_blank">Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022</a></li>
<li> <a href="https://doi.org/10.48550/arXiv.2310.20360" target="_blank">Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger</a></li>
</ol>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lecture-monday-october-7">Lecture Monday October 7 </h2>
<h2 id="reminder-on-books-with-hands-on-material-and-codes">Reminder on books with hands-on material and codes </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ul>
<li> <a href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" target="_blank">Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch</a></li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lab-sessions-on-tuesday-and-wednesday">Lab sessions on Tuesday and Wednesday </h2>
<ol>
<li> Getting started with coding neural network. The exercises this week aim at setting up the feed-forward part of a neural network.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lecture-monday-october-6">Lecture Monday October 6 </h2>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="introduction-to-neural-networks">Introduction to Neural networks </h2>
@@ -674,211 +626,6 @@ as to not restrict the range of output values.
<p><img src="figures/nns.png" width="600" align="bottom"></p>
</center>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="examples-of-xor-or-and-and-gates">Examples of XOR, OR and AND gates </h2>
<p>Let us first try to fit various gates using standard linear
regression. The gates we are thinking of are the classical XOR, OR and
AND gates, well-known elements in computer science. The tables here
show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a
specific target \( y_i \).
</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #CD5555">&quot;&quot;&quot;</span>
<span style="color: #CD5555">Simple code that tests XOR, OR and AND gates with linear regression</span>
<span style="color: #CD5555">&quot;&quot;&quot;</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #228B22"># Design matrix</span>
X = np.array([ [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>, <span style="color: #B452CD">0</span>], [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>], [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>],[<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>]],dtype=np.float64)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The X.TX matrix:{</span>X.T @ X<span style="color: #CD5555">}&quot;</span>)
Xinv = np.linalg.pinv(X.T @ X)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The invers of X.TX matrix:{</span>Xinv<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The XOR gate </span>
yXOR = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span> ,<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>])
ThetaXOR = Xinv @ X.T @ yXOR
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the XOR gate:{</span>ThetaXOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the XOR gate:{</span>X @ ThetaXOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The OR gate </span>
yOR = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span> ,<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>])
ThetaOR = Xinv @ X.T @ yOR
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the OR gate:{</span>ThetaOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the OR gate:{</span>X @ ThetaOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The OR gate </span>
yAND = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">0</span> ,<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>])
ThetaAND = Xinv @ X.T @ yAND
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the AND gate:{</span>ThetaAND<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the AND gate:{</span>X @ ThetaAND<span style="color: #CD5555">}&quot;</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>What is happening here?</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="does-logistic-regression-do-a-better-job">Does Logistic Regression do a better Job? </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #CD5555">&quot;&quot;&quot;</span>
<span style="color: #CD5555">Simple code that tests XOR and OR gates with linear regression</span>
<span style="color: #CD5555">and logistic regression</span>
<span style="color: #CD5555">&quot;&quot;&quot;</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.linear_model</span> <span style="color: #8B008B; font-weight: bold">import</span> LogisticRegression
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #228B22"># Design matrix</span>
X = np.array([ [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>, <span style="color: #B452CD">0</span>], [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>], [<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>],[<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>]],dtype=np.float64)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The X.TX matrix:{</span>X.T @ X<span style="color: #CD5555">}&quot;</span>)
Xinv = np.linalg.pinv(X.T @ X)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The invers of X.TX matrix:{</span>Xinv<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The XOR gate </span>
yXOR = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span> ,<span style="color: #B452CD">1</span>, <span style="color: #B452CD">0</span>])
ThetaXOR = Xinv @ X.T @ yXOR
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the XOR gate:{</span>ThetaXOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the XOR gate:{</span>X @ ThetaXOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The OR gate </span>
yOR = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span> ,<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>])
ThetaOR = Xinv @ X.T @ yOR
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the OR gate:{</span>ThetaOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the OR gate:{</span>X @ ThetaOR<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># The OR gate </span>
yAND = np.array( [ <span style="color: #B452CD">0</span>, <span style="color: #B452CD">0</span> ,<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>])
ThetaAND = Xinv @ X.T @ yAND
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The values of theta for the AND gate:{</span>ThetaAND<span style="color: #CD5555">}&quot;</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;The linear regression prediction for the AND gate:{</span>X @ ThetaAND<span style="color: #CD5555">}&quot;</span>)
<span style="color: #228B22"># Now we change to logistic regression</span>
<span style="color: #228B22"># Logistic Regression</span>
logreg = LogisticRegression()
logreg.fit(X, yOR)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy with Logistic Regression for OR gate: {:.2f}&quot;</span>.format(logreg.score(X,yOR)))
logreg.fit(X, yXOR)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy with Logistic Regression for XOR gate: {:.2f}&quot;</span>.format(logreg.score(X,yXOR)))
logreg.fit(X, yAND)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy with Logistic Regression for AND gate: {:.2f}&quot;</span>.format(logreg.score(X,yAND)))
</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>Not exactly impressive, but somewhat better.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="adding-neural-networks">Adding Neural Networks </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #228B22"># and now neural networks with Scikit-Learn and the XOR</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.neural_network</span> <span style="color: #8B008B; font-weight: bold">import</span> MLPClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.datasets</span> <span style="color: #8B008B; font-weight: bold">import</span> make_classification
X, yXOR = make_classification(n_samples=<span style="color: #B452CD">100</span>, random_state=<span style="color: #B452CD">1</span>)
FFNN = MLPClassifier(random_state=<span style="color: #B452CD">1</span>, max_iter=<span style="color: #B452CD">300</span>).fit(X, yXOR)
FFNN.predict_proba(X)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">f&quot;Test set accuracy with Feed Forward Neural Network for XOR gate:{</span>FFNN.score(X, yXOR)<span style="color: #CD5555">}&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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="mathematics-of-deep-learning">Mathematics of deep learning </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Two recent books online</b>
<p>
<ol>
<li> <a href="https://arxiv.org/abs/2105.04026" target="_blank">The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen</a>, published as <a href="https://doi.org/10.1017/9781009025096.002" target="_blank">Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022</a></li>
<li> <a href="https://doi.org/10.48550/arXiv.2310.20360" target="_blank">Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger</a></li>
</ol>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="reminder-on-books-with-hands-on-material-and-codes">Reminder on books with hands-on material and codes </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ul>
<li> <a href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" target="_blank">Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch</a></li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="reading-recommendations">Reading recommendations </h2>
<ol>
<li> Rashkca et al., chapter 11, jupyter-notebook sent separately, from <a href="https://github.com/rasbt/machine-learning-book" target="_blank">GitHub</a></li>
<li> Goodfellow et al, chapter 6 and 7 contain most of the neural network background.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="mathematics-of-deep-learning-and-neural-networks">Mathematics of deep learning and neural networks </h2>
@@ -1192,7 +939,7 @@ $$
<p>In order to understand the back propagation algorithm and its
derivation (an implementation of the chain rule), let us first digress
with some simple examples. These examples are also meant to motivate
the link with back propagation and <a href="https://en.wikipedia.org/wiki/Automatic_differentiation" target="_blank">automatic differentiation</a>.
the link with back propagation and <a href="https://en.wikipedia.org/wiki/Automatic_differentiation" target="_blank">automatic differentiation</a>. We will discuss these topics next week (week 42).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -1226,7 +973,9 @@ $$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="automatic-differentiation-through-examples">Automatic differentiation through examples </h2>
<p>A great introduction to automatic differentiation is given by Baydin et al., see <a href="https://arxiv.org/abs/1502.05767" target="_blank"><tt>https://arxiv.org/abs/1502.05767</tt></a>.</p>
<p>A great introduction to automatic differentiation is given by Baydin et al., see <a href="https://arxiv.org/abs/1502.05767" target="_blank"><tt>https://arxiv.org/abs/1502.05767</tt></a>.
See also the video at <a href="https://www.youtube.com/watch?v=wG_nF1awSSY" target="_blank"><tt>https://www.youtube.com/watch?v=wG_nF1awSSY</tt></a>.
</p>
<p>Automatic differentiation is a represented by a repeated application
of the chain rule on well-known functions and allows for the
@@ -2265,487 +2014,9 @@ b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h3 id="activation-functions">Activation functions </h3>
<p>A property that characterizes a neural network, other than its
connectivity, is the choice of activation function(s). As described
in, the following restrictions are imposed on an activation function
for a FFNN to fulfill the universal approximation theorem
</p>
<ul>
<li> Non-constant</li>
<li> Bounded</li>
<li> Monotonically-increasing</li>
<li> Continuous</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h3 id="activation-functions-logistic-and-hyperbolic-ones">Activation functions, Logistic and Hyperbolic ones </h3>
<p>The second requirement excludes all linear functions. Furthermore, in
a MLP with only linear activation functions, each layer simply
performs a linear transformation of its inputs.
</p>
<p>Regardless of the number of layers, the output of the NN will be
nothing but a linear function of the inputs. Thus we need to introduce
some kind of non-linearity to the NN to be able to fit non-linear
functions Typical examples are the logistic <em>Sigmoid</em>
</p>
$$
f(x) = \frac{1}{1 + e^{-x}},
$$
<p>and the <em>hyperbolic tangent</em> function</p>
$$
f(x) = \tanh(x)
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h3 id="relevance">Relevance </h3>
<p>The <em>sigmoid</em> function are more biologically plausible because the
output of inactive neurons are zero. Such activation function are
called <em>one-sided</em>. However, it has been shown that the hyperbolic
tangent performs better than the sigmoid for training MLPs. has
become the most popular for <em>deep neural networks</em>
</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #eeeedd">
<pre style="line-height: 125%;"><span style="color: #CD5555">&quot;&quot;&quot;The sigmoid function (or the logistic curve) is a </span>
<span style="color: #CD5555">function that takes any real number, z, and outputs a number (0,1).</span>
<span style="color: #CD5555">It is useful in neural networks for assigning weights on a relative scale.</span>
<span style="color: #CD5555">The value z is the weighted sum of parameters involved in the learning algorithm.&quot;&quot;&quot;</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">math</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">mt</span>
z = numpy.arange(-<span style="color: #B452CD">5</span>, <span style="color: #B452CD">5</span>, <span style="color: #B452CD">.1</span>)
sigma_fn = numpy.vectorize(<span style="color: #8B008B; font-weight: bold">lambda</span> z: <span style="color: #B452CD">1</span>/(<span style="color: #B452CD">1</span>+numpy.exp(-z)))
sigma = sigma_fn(z)
fig = plt.figure()
ax = fig.add_subplot(<span style="color: #B452CD">111</span>)
ax.plot(z, sigma)
ax.set_ylim([-<span style="color: #B452CD">0.1</span>, <span style="color: #B452CD">1.1</span>])
ax.set_xlim([-<span style="color: #B452CD">5</span>,<span style="color: #B452CD">5</span>])
ax.grid(<span style="color: #8B008B; font-weight: bold">True</span>)
ax.set_xlabel(<span style="color: #CD5555">&#39;z&#39;</span>)
ax.set_title(<span style="color: #CD5555">&#39;sigmoid function&#39;</span>)
plt.show()
<span style="color: #CD5555">&quot;&quot;&quot;Step Function&quot;&quot;&quot;</span>
z = numpy.arange(-<span style="color: #B452CD">5</span>, <span style="color: #B452CD">5</span>, <span style="color: #B452CD">.02</span>)
step_fn = numpy.vectorize(<span style="color: #8B008B; font-weight: bold">lambda</span> z: <span style="color: #B452CD">1.0</span> <span style="color: #8B008B; font-weight: bold">if</span> z &gt;= <span style="color: #B452CD">0.0</span> <span style="color: #8B008B; font-weight: bold">else</span> <span style="color: #B452CD">0.0</span>)
step = step_fn(z)
fig = plt.figure()
ax = fig.add_subplot(<span style="color: #B452CD">111</span>)
ax.plot(z, step)
ax.set_ylim([-<span style="color: #B452CD">0.5</span>, <span style="color: #B452CD">1.5</span>])
ax.set_xlim([-<span style="color: #B452CD">5</span>,<span style="color: #B452CD">5</span>])
ax.grid(<span style="color: #8B008B; font-weight: bold">True</span>)
ax.set_xlabel(<span style="color: #CD5555">&#39;z&#39;</span>)
ax.set_title(<span style="color: #CD5555">&#39;step function&#39;</span>)
plt.show()
<span style="color: #CD5555">&quot;&quot;&quot;Sine Function&quot;&quot;&quot;</span>
z = numpy.arange(-<span style="color: #B452CD">2</span>*mt.pi, <span style="color: #B452CD">2</span>*mt.pi, <span style="color: #B452CD">0.1</span>)
t = numpy.sin(z)
fig = plt.figure()
ax = fig.add_subplot(<span style="color: #B452CD">111</span>)
ax.plot(z, t)
ax.set_ylim([-<span style="color: #B452CD">1.0</span>, <span style="color: #B452CD">1.0</span>])
ax.set_xlim([-<span style="color: #B452CD">2</span>*mt.pi,<span style="color: #B452CD">2</span>*mt.pi])
ax.grid(<span style="color: #8B008B; font-weight: bold">True</span>)
ax.set_xlabel(<span style="color: #CD5555">&#39;z&#39;</span>)
ax.set_title(<span style="color: #CD5555">&#39;sine function&#39;</span>)
plt.show()
<span style="color: #CD5555">&quot;&quot;&quot;Plots a graph of the squashing function used by a rectified linear</span>
<span style="color: #CD5555">unit&quot;&quot;&quot;</span>
z = numpy.arange(-<span style="color: #B452CD">2</span>, <span style="color: #B452CD">2</span>, <span style="color: #B452CD">.1</span>)
zero = numpy.zeros(<span style="color: #658b00">len</span>(z))
y = numpy.max([zero, z], axis=<span style="color: #B452CD">0</span>)
fig = plt.figure()
ax = fig.add_subplot(<span style="color: #B452CD">111</span>)
ax.plot(z, y)
ax.set_ylim([-<span style="color: #B452CD">2.0</span>, <span style="color: #B452CD">2.0</span>])
ax.set_xlim([-<span style="color: #B452CD">2.0</span>, <span style="color: #B452CD">2.0</span>])
ax.grid(<span style="color: #8B008B; font-weight: bold">True</span>)
ax.set_xlabel(<span style="color: #CD5555">&#39;z&#39;</span>)
ax.set_title(<span style="color: #CD5555">&#39;Rectified linear unit&#39;</span>)
plt.show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="fine-tuning-neural-network-hyperparameters">Fine-tuning neural network hyperparameters </h2>
<p>The flexibility of neural networks is also one of their main
drawbacks: there are many hyperparameters to tweak. Not only can you
use any imaginable network topology (how neurons/nodes are
interconnected), but even in a simple FFNN you can change the number
of layers, the number of neurons per layer, the type of activation
function to use in each layer, the weight initialization logic, the
stochastic gradient optmized and much more. How do you know what
combination of hyperparameters is the best for your task?
</p>
<ul>
<li> You can use grid search with cross-validation to find the right hyperparameters.</li>
</ul>
<p>However,since there are many hyperparameters to tune, and since
training a neural network on a large dataset takes a lot of time, you
will only be able to explore a tiny part of the hyperparameter space.
</p>
<ul>
<li> You can use randomized search.</li>
<li> Or use tools like <a href="http://oscar.calldesk.ai/" target="_blank">Oscar</a>, which implements more complex algorithms to help you find a good set of hyperparameters quickly.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="hidden-layers">Hidden layers </h2>
<p>For many problems you can start with just one or two hidden layers and
it will work just fine. For the MNIST data set you ca easily get a
high accuracy using just one hidden layer with a few hundred neurons.
You can reach for this data set above 98% accuracy using two hidden
layers with the same total amount of neurons, in roughly the same
amount of training time.
</p>
<p>For more complex problems, you can gradually ramp up the number of
hidden layers, until you start overfitting the training set. Very
complex tasks, such as large image classification or speech
recognition, typically require networks with dozens of layers and they
need a huge amount of training data. However, you will rarely have to
train such networks from scratch: it is much more common to reuse
parts of a pretrained state-of-the-art network that performs a similar
task.
</p>
<!-- !split -->
<h2 id="vanishing-gradients">Vanishing gradients </h2>
<p>The Back propagation algorithm we derived above works by going from
the output layer to the input layer, propagating the error gradient on
the way. Once the algorithm has computed the gradient of the cost
function with regards to each parameter in the network, it uses these
gradients to update each parameter with a Gradient Descent (GD) step.
</p>
<p>Unfortunately for us, the gradients often get smaller and smaller as
the algorithm progresses down to the first hidden layers. As a result,
the GD update leaves the lower layer connection weights virtually
unchanged, and training never converges to a good solution. This is
known in the literature as <b>the vanishing gradients problem</b>.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="exploding-gradients">Exploding gradients </h2>
<p>In other cases, the opposite can happen, namely the the gradients can
grow bigger and bigger. The result is that many of the layers get
large updates of the weights the algorithm diverges. This is the
<b>exploding gradients problem</b>, which is mostly encountered in
recurrent neural networks. More generally, deep neural networks suffer
from unstable gradients, different layers may learn at widely
different speeds
</p>
<!-- !split -->
<h2 id="is-the-logistic-activation-function-sigmoid-our-choice">Is the Logistic activation function (Sigmoid) our choice? </h2>
<p>Although this unfortunate behavior has been empirically observed for
quite a while (it was one of the reasons why deep neural networks were
mostly abandoned for a long time), it is only around 2010 that
significant progress was made in understanding it.
</p>
<p>A paper titled <a href="http://proceedings.mlr.press/v9/glorot10a.html" target="_blank">Understanding the Difficulty of Training Deep
Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio</a> found that
the problems with the popular logistic
sigmoid activation function and the weight initialization technique
that was most popular at the time, namely random initialization using
a normal distribution with a mean of 0 and a standard deviation of
1.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="logistic-function-as-the-root-of-problems">Logistic function as the root of problems </h2>
<p>They showed that with this activation function and this
initialization scheme, the variance of the outputs of each layer is
much greater than the variance of its inputs. Going forward in the
network, the variance keeps increasing after each layer until the
activation function saturates at the top layers. This is actually made
worse by the fact that the logistic function has a mean of 0.5, not 0
(the hyperbolic tangent function has a mean of 0 and behaves slightly
better than the logistic function in deep networks).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-derivative-of-the-logistic-funtion">The derivative of the Logistic funtion </h2>
<p>Looking at the logistic activation function, when inputs become large
(negative or positive), the function saturates at 0 or 1, with a
derivative extremely close to 0. Thus when backpropagation kicks in,
it has virtually no gradient to propagate back through the network,
and what little gradient exists keeps getting diluted as
backpropagation progresses down through the top layers, so there is
really nothing left for the lower layers.
</p>
<p>In their paper, Glorot and Bengio propose a way to significantly
alleviate this problem. We need the signal to flow properly in both
directions: in the forward direction when making predictions, and in
the reverse direction when backpropagating gradients. We don&#8217;t want
the signal to die out, nor do we want it to explode and saturate. For
the signal to flow properly, the authors argue that we need the
variance of the outputs of each layer to be equal to the variance of
its inputs, and we also need the gradients to have equal variance
before and after flowing through a layer in the reverse direction.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="insights-from-the-paper-by-glorot-and-bengio">Insights from the paper by Glorot and Bengio </h2>
<p>One of the insights in the 2010 paper by Glorot and Bengio was that
the vanishing/exploding gradients problems were in part due to a poor
choice of activation function. Until then most people had assumed that
if Nature had chosen to use roughly sigmoid activation functions in
biological neurons, they must be an excellent choice. But it turns out
that other activation functions behave much better in deep neural
networks, in particular the ReLU activation function, mostly because
it does not saturate for positive values (and also because it is quite
fast to compute).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-relu-function-family">The RELU function family </h2>
<p>The ReLU activation function suffers from a problem known as the dying
ReLUs: during training, some neurons effectively die, meaning they
stop outputting anything other than 0.
</p>
<p>In some cases, you may find that half of your network&#8217;s neurons are
dead, especially if you used a large learning rate. During training,
if a neuron&#8217;s weights get updated such that the weighted sum of the
neuron&#8217;s inputs is negative, it will start outputting 0. When this
happen, the neuron is unlikely to come back to life since the gradient
of the ReLU function is 0 when its input is negative.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="elu-function">ELU function </h2>
<p>To solve this problem, nowadays practitioners use a variant of the
ReLU function, such as the leaky ReLU discussed above or the so-called
exponential linear unit (ELU) function
</p>
$$
ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="which-activation-function-should-we-use">Which activation function should we use? </h2>
<p>In general it seems that the ELU activation function is better than
the leaky ReLU function (and its variants), which is better than
ReLU. ReLU performs better than \( \tanh \) which in turn performs better
than the logistic function.
</p>
<p>If runtime performance is an issue, then you may opt for the leaky
ReLU function over the ELU function If you don&#8217;t want to tweak yet
another hyperparameter, you may just use the default \( \alpha \) of
\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and
computing power, you can use cross-validation or bootstrap to evaluate
other activation functions.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-on-activation-functions-output-layers">More on activation functions, output layers </h2>
<p>In most cases you can use the ReLU activation function in the hidden
layers (or one of its variants).
</p>
<p>It is a bit faster to compute than other activation functions, and the
gradient descent optimization does in general not get stuck.
</p>
<b>For the output layer:</b>
<ul>
<li> For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).</li>
<li> For regression tasks, you can simply use no activation function at all.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="batch-normalization">Batch Normalization </h2>
<p>Batch Normalization aims to address the vanishing/exploding gradients
problems, and more generally the problem that the distribution of each
layer&#8217;s inputs changes during training, as the parameters of the
previous layers change.
</p>
<p>The technique consists of adding an operation in the model just before
the activation function of each layer, simply zero-centering and
normalizing the inputs, then scaling and shifting the result using two
new parameters per layer (one for scaling, the other for shifting). In
other words, this operation lets the model learn the optimal scale and
mean of the inputs for each layer. In order to zero-center and
normalize the inputs, the algorithm needs to estimate the inputs&#8217; mean
and standard deviation. It does so by evaluating the mean and standard
deviation of the inputs over the current mini-batch, from this the
name batch normalization.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="dropout">Dropout </h2>
<p>It is a fairly simple algorithm: at every training step, every neuron
(including the input neurons but excluding the output neurons) has a
probability \( p \) of being temporarily dropped out, meaning it will be
entirely ignored during this training step, but it may be active
during the next step.
</p>
<p>The hyperparameter \( p \) is called the dropout rate, and it is typically
set to 50%. After training, the neurons are not dropped anymore. It
is viewed as one of the most popular regularization techniques.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="gradient-clipping">Gradient Clipping </h2>
<p>A popular technique to lessen the exploding gradients problem is to
simply clip the gradients during backpropagation so that they never
exceed some threshold (this is mostly useful for recurrent neural
networks).
</p>
<p>This technique is called Gradient Clipping.</p>
<p>In general however, Batch
Normalization is preferred.
</p>
<!-- !split -->
<h2 id="a-top-down-perspective-on-neural-networks">A top-down perspective on Neural networks </h2>
<p>The first thing we would like to do is divide the data into two or
three parts. A training set, a validation or dev (development) set,
and a test set. The test set is the data on which we want to make
predictions. The dev set is a subset of the training data we use to
check how well we are doing out-of-sample, after training the model on
the training dataset. We use the validation error as a proxy for the
test error in order to make tweaks to our model. It is crucial that we
do not use any of the test data to train the algorithm. This is a
cardinal sin in ML. Then:
</p>
<ol>
<li> Estimate optimal error rate</li>
<li> Minimize underfitting (bias) on training data set.</li>
<li> Make sure you are not overfitting.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-top-down-perspectives">More top-down perspectives </h2>
<p>If the validation and test sets are drawn from the same distributions,
then a good performance on the validation set should lead to similarly
good performance on the test set.
</p>
<p>However, sometimes
the training data and test data differ in subtle ways because, for
example, they are collected using slightly different methods, or
because it is cheaper to collect data in one way versus another. In
this case, there can be a mismatch between the training and test
data. This can lead to the neural network overfitting these small
differences between the test and training sets, and a poor performance
on the test set despite having a good performance on the validation
set. To rectify this, Andrew Ng suggests making two validation or dev
sets, one constructed from the training data and one constructed from
the test data. The difference between the performance of the algorithm
on these two validation sets quantifies the train-test mismatch. This
can serve as another important diagnostic when using DNNs for
supervised learning.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="limitations-of-supervised-learning-with-deep-networks">Limitations of supervised learning with deep networks </h2>
<p>Like all statistical methods, supervised learning using neural
networks has important limitations. This is especially important when
one seeks to apply these methods, especially to physics problems. Like
all tools, DNNs are not a universal solution. Often, the same or
better performance on a task can be achieved by using a few
hand-engineered features (or even a collection of random
features).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="limitations-of-nns">Limitations of NNs </h2>
<p>Here we list some of the important limitations of supervised neural network based models. </p>
<ul>
<li> <b>Need labeled data</b>. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).</li>
<li> <b>Supervised neural networks are extremely data intensive.</b> DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="homogeneous-data">Homogeneous data </h2>
<ul>
<li> <b>Homogeneous data.</b> Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e.&nbsp;some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-limitations">More limitations </h2>
<ul>
<li> <b>Many problems are not about prediction.</b> In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a <em>wrong</em> model. The model might or might not be useful for understanding the underlying science.</li>
</ul>
<p>Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.</p>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
<!-- copyright --> &copy; 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>
+61 -790
View File
@@ -140,23 +140,30 @@ div.toc p,a {
<!-- tocinfo
{'highest level': 2,
'sections': [('Plan for week 41, October 7-11',
'sections': [('Plan for week 41, October 6-10',
2,
None,
'plan-for-week-41-october-7-11'),
('Material for the lecture on Monday October 7, 2024',
'plan-for-week-41-october-6-10'),
('Material for the lecture on Monday October 6, 2025',
2,
None,
'material-for-the-lecture-on-monday-october-7-2024'),
('Material for the active learning sessions on Tuesday and '
'Wednesday',
'material-for-the-lecture-on-monday-october-6-2025'),
('Mathematics of deep learning',
2,
None,
'material-for-the-active-learning-sessions-on-tuesday-and-wednesday'),
('Lecture Monday October 7',
'mathematics-of-deep-learning'),
('Reminder on books with hands-on material and codes',
2,
None,
'lecture-monday-october-7'),
'reminder-on-books-with-hands-on-material-and-codes'),
('Lab sessions on Tuesday and Wednesday',
2,
None,
'lab-sessions-on-tuesday-and-wednesday'),
('Lecture Monday October 6',
2,
None,
'lecture-monday-october-6'),
('Introduction to Neural networks',
2,
None,
@@ -186,24 +193,6 @@ div.toc p,a {
2,
None,
'illustration-of-a-single-perceptron-model-and-a-multi-perceptron-model'),
('Examples of XOR, OR and AND gates',
2,
None,
'examples-of-xor-or-and-and-gates'),
('Does Logistic Regression do a better Job?',
2,
None,
'does-logistic-regression-do-a-better-job'),
('Adding Neural Networks', 2, None, 'adding-neural-networks'),
('Mathematics of deep learning',
2,
None,
'mathematics-of-deep-learning'),
('Reminder on books with hands-on material and codes',
2,
None,
'reminder-on-books-with-hands-on-material-and-codes'),
('Reading recommendations', 2, None, 'reading-recommendations'),
('Mathematics of deep learning and neural networks',
2,
None,
@@ -408,64 +397,7 @@ div.toc p,a {
2,
None,
'setting-up-the-back-propagation-algorithm-part-3'),
('Updating the gradients', 2, None, 'updating-the-gradients'),
('Activation functions', 3, None, 'activation-functions'),
('Activation functions, Logistic and Hyperbolic ones',
3,
None,
'activation-functions-logistic-and-hyperbolic-ones'),
('Relevance', 3, None, 'relevance'),
('Fine-tuning neural network hyperparameters',
2,
None,
'fine-tuning-neural-network-hyperparameters'),
('Hidden layers', 2, None, 'hidden-layers'),
('Vanishing gradients', 2, None, 'vanishing-gradients'),
('Exploding gradients', 2, None, 'exploding-gradients'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
'is-the-logistic-activation-function-sigmoid-our-choice'),
('Logistic function as the root of problems',
2,
None,
'logistic-function-as-the-root-of-problems'),
('The derivative of the Logistic funtion',
2,
None,
'the-derivative-of-the-logistic-funtion'),
('Insights from the paper by Glorot and Bengio',
2,
None,
'insights-from-the-paper-by-glorot-and-bengio'),
('The RELU function family', 2, None, 'the-relu-function-family'),
('ELU function', 2, None, 'elu-function'),
('Which activation function should we use?',
2,
None,
'which-activation-function-should-we-use'),
('More on activation functions, output layers',
2,
None,
'more-on-activation-functions-output-layers'),
('Batch Normalization', 2, None, 'batch-normalization'),
('Dropout', 2, None, 'dropout'),
('Gradient Clipping', 2, None, 'gradient-clipping'),
('A top-down perspective on Neural networks',
2,
None,
'a-top-down-perspective-on-neural-networks'),
('More top-down perspectives',
2,
None,
'more-top-down-perspectives'),
('Limitations of supervised learning with deep networks',
2,
None,
'limitations-of-supervised-learning-with-deep-networks'),
('Limitations of NNs', 2, None, 'limitations-of-nns'),
('Homogeneous data', 2, None, 'homogeneous-data'),
('More limitations', 2, None, 'more-limitations')]}
('Updating the gradients', 2, None, 'updating-the-gradients')]}
end of tocinfo -->
<body>
@@ -496,7 +428,7 @@ MathJax.Hub.Config({
</center>
<!-- institution -->
<center>
<b>Department of Physics, University of Oslo</b>
<b>Department of Physics, University of Oslo, Norway</b>
</center>
<br>
<center>
@@ -505,27 +437,25 @@ MathJax.Hub.Config({
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plan-for-week-41-october-7-11">Plan for week 41, October 7-11 </h2>
<h2 id="plan-for-week-41-october-6-10">Plan for week 41, October 6-10 </h2>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="material-for-the-lecture-on-monday-october-7-2024">Material for the lecture on Monday October 7, 2024 </h2>
<h2 id="material-for-the-lecture-on-monday-october-6-2025">Material for the lecture on Monday October 6, 2025 </h2>
<ol>
<li> Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.</li>
<li> Building our own Feed-forward Neural Network</li>
<ul>
<li> Video of lecture notes at <a href="https://youtu.be/pMRUbf9E-gM" target="_blank"><tt>https://youtu.be/pMRUbf9E-gM</tt></a></li>
<li> Whiteboard notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf</tt></a></li>
</ul>
<li> Building our own Feed-forward Neural Network, getting started
<!-- * Video of lecture notes at <a href="https://youtu.be/pMRUbf9E-gM" target="_blank"><tt>https://youtu.be/pMRUbf9E-gM</tt></a> -->
<!-- * Whiteboard notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf</tt></a> --></li>
</ol>
<div class="alert alert-block alert-block alert-text-normal">
<b>Readings and Videos:</b>
<p>
<ol>
<li> These lecture notes</li>
<li> Rashcka et al chapter 11</li>
<li> For neural networks we recommend Goodfellow et al chapter 6.
<li> For neural networks we recommend Goodfellow et al chapters 6 and 7.</li>
<li> Rashkca et al., chapter 11, jupyter-notebook sent separately, from <a href="https://github.com/rasbt/machine-learning-book" target="_blank">GitHub</a>
<ol type="a"></li>
<li> Neural Networks demystified at <a href="https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" target="_blank"><tt>https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs</tt></a></li>
<li> Neural Networks demystified at <a href="https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" target="_blank"><tt>https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs</tt></a></li>
</ol>
<li> Building Neural Networks from scratch at <a href="https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex" target="_blank"><tt>https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex</tt></a></li>
<li> Video on Neural Networks at <a href="https://www.youtube.com/watch?v=CqOfi41LfDw" target="_blank"><tt>https://www.youtube.com/watch?v=CqOfi41LfDw</tt></a></li>
@@ -536,15 +466,37 @@ MathJax.Hub.Config({
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="material-for-the-active-learning-sessions-on-tuesday-and-wednesday">Material for the active learning sessions on Tuesday and Wednesday </h2>
<ul>
<li> Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation</li>
<li> One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code</li>
<li> Discussion of project 2</li>
<li> Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent</li>
</ul>
<h2 id="mathematics-of-deep-learning">Mathematics of deep learning </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Two recent books online</b>
<p>
<ol>
<li> <a href="https://arxiv.org/abs/2105.04026" target="_blank">The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen</a>, published as <a href="https://doi.org/10.1017/9781009025096.002" target="_blank">Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022</a></li>
<li> <a href="https://doi.org/10.48550/arXiv.2310.20360" target="_blank">Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger</a></li>
</ol>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lecture-monday-october-7">Lecture Monday October 7 </h2>
<h2 id="reminder-on-books-with-hands-on-material-and-codes">Reminder on books with hands-on material and codes </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ul>
<li> <a href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" target="_blank">Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch</a></li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lab-sessions-on-tuesday-and-wednesday">Lab sessions on Tuesday and Wednesday </h2>
<ol>
<li> Getting started with coding neural network. The exercises this week aim at setting up the feed-forward part of a neural network.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lecture-monday-october-6">Lecture Monday October 6 </h2>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="introduction-to-neural-networks">Introduction to Neural networks </h2>
@@ -751,211 +703,6 @@ as to not restrict the range of output values.
<p><img src="figures/nns.png" width="600" align="bottom"></p>
</center>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="examples-of-xor-or-and-and-gates">Examples of XOR, OR and AND gates </h2>
<p>Let us first try to fit various gates using standard linear
regression. The gates we are thinking of are the classical XOR, OR and
AND gates, well-known elements in computer science. The tables here
show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a
specific target \( y_i \).
</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: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic">Simple code that tests XOR, OR and AND gates with linear regression</span>
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #408080; font-style: italic"># Design matrix</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([ [<span style="color: #666666">1</span>, <span style="color: #666666">0</span>, <span style="color: #666666">0</span>], [<span style="color: #666666">1</span>, <span style="color: #666666">0</span>, <span style="color: #666666">1</span>], [<span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0</span>],[<span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>]],dtype<span style="color: #666666">=</span>np<span style="color: #666666">.</span>float64)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The X.TX matrix:</span><span style="color: #BB6688; font-weight: bold">{</span>X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
Xinv <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>pinv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The invers of X.TX matrix:</span><span style="color: #BB6688; font-weight: bold">{</span>Xinv<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #408080; font-style: italic"># The XOR gate </span>
yXOR <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ <span style="color: #666666">0</span>, <span style="color: #666666">1</span> ,<span style="color: #666666">1</span>, <span style="color: #666666">0</span>])
ThetaXOR <span style="color: #666666">=</span> Xinv <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> yXOR
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The values of theta for the XOR gate:</span><span style="color: #BB6688; font-weight: bold">{</span>ThetaXOR<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The linear regression prediction for the XOR gate:</span><span style="color: #BB6688; font-weight: bold">{</span>X <span style="color: #666666">@</span> ThetaXOR<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #408080; font-style: italic"># The OR gate </span>
yOR <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ <span style="color: #666666">0</span>, <span style="color: #666666">1</span> ,<span style="color: #666666">1</span>, <span style="color: #666666">1</span>])
ThetaOR <span style="color: #666666">=</span> Xinv <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> yOR
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The values of theta for the OR gate:</span><span style="color: #BB6688; font-weight: bold">{</span>ThetaOR<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The linear regression prediction for the OR gate:</span><span style="color: #BB6688; font-weight: bold">{</span>X <span style="color: #666666">@</span> ThetaOR<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #408080; font-style: italic"># The OR gate </span>
yAND <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ <span style="color: #666666">0</span>, <span style="color: #666666">0</span> ,<span style="color: #666666">0</span>, <span style="color: #666666">1</span>])
ThetaAND <span style="color: #666666">=</span> Xinv <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> yAND
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The values of theta for the AND gate:</span><span style="color: #BB6688; font-weight: bold">{</span>ThetaAND<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The linear regression prediction for the AND gate:</span><span style="color: #BB6688; font-weight: bold">{</span>X <span style="color: #666666">@</span> ThetaAND<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>
<p>What is happening here?</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="does-logistic-regression-do-a-better-job">Does Logistic Regression do a better Job? </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic">Simple code that tests XOR and OR gates with linear regression</span>
<span style="color: #BA2121; font-style: italic">and logistic regression</span>
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #408080; font-style: italic"># Design matrix</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([ [<span style="color: #666666">1</span>, <span style="color: #666666">0</span>, <span style="color: #666666">0</span>], [<span style="color: #666666">1</span>, <span style="color: #666666">0</span>, <span style="color: #666666">1</span>], [<span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0</span>],[<span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>]],dtype<span style="color: #666666">=</span>np<span style="color: #666666">.</span>float64)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The X.TX matrix:</span><span style="color: #BB6688; font-weight: bold">{</span>X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
Xinv <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>pinv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The invers of X.TX matrix:</span><span style="color: #BB6688; font-weight: bold">{</span>Xinv<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #408080; font-style: italic"># The XOR gate </span>
yXOR <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ <span style="color: #666666">0</span>, <span style="color: #666666">1</span> ,<span style="color: #666666">1</span>, <span style="color: #666666">0</span>])
ThetaXOR <span style="color: #666666">=</span> Xinv <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> yXOR
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The values of theta for the XOR gate:</span><span style="color: #BB6688; font-weight: bold">{</span>ThetaXOR<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The linear regression prediction for the XOR gate:</span><span style="color: #BB6688; font-weight: bold">{</span>X <span style="color: #666666">@</span> ThetaXOR<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #408080; font-style: italic"># The OR gate </span>
yOR <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ <span style="color: #666666">0</span>, <span style="color: #666666">1</span> ,<span style="color: #666666">1</span>, <span style="color: #666666">1</span>])
ThetaOR <span style="color: #666666">=</span> Xinv <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> yOR
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The values of theta for the OR gate:</span><span style="color: #BB6688; font-weight: bold">{</span>ThetaOR<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The linear regression prediction for the OR gate:</span><span style="color: #BB6688; font-weight: bold">{</span>X <span style="color: #666666">@</span> ThetaOR<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #408080; font-style: italic"># The OR gate </span>
yAND <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [ <span style="color: #666666">0</span>, <span style="color: #666666">0</span> ,<span style="color: #666666">0</span>, <span style="color: #666666">1</span>])
ThetaAND <span style="color: #666666">=</span> Xinv <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> yAND
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The values of theta for the AND gate:</span><span style="color: #BB6688; font-weight: bold">{</span>ThetaAND<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;The linear regression prediction for the AND gate:</span><span style="color: #BB6688; font-weight: bold">{</span>X <span style="color: #666666">@</span> ThetaAND<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #408080; font-style: italic"># Now we change to logistic regression</span>
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
logreg <span style="color: #666666">=</span> LogisticRegression()
logreg<span style="color: #666666">.</span>fit(X, yOR)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with Logistic Regression for OR gate: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X,yOR)))
logreg<span style="color: #666666">.</span>fit(X, yXOR)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with Logistic Regression for XOR gate: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X,yXOR)))
logreg<span style="color: #666666">.</span>fit(X, yAND)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with Logistic Regression for AND gate: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X,yAND)))
</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>Not exactly impressive, but somewhat better.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="adding-neural-networks">Adding Neural Networks </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># and now neural networks with Scikit-Learn and the XOR</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.neural_network</span> <span style="color: #008000; font-weight: bold">import</span> MLPClassifier
<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> make_classification
X, yXOR <span style="color: #666666">=</span> make_classification(n_samples<span style="color: #666666">=100</span>, random_state<span style="color: #666666">=1</span>)
FFNN <span style="color: #666666">=</span> MLPClassifier(random_state<span style="color: #666666">=1</span>, max_iter<span style="color: #666666">=300</span>)<span style="color: #666666">.</span>fit(X, yXOR)
FFNN<span style="color: #666666">.</span>predict_proba(X)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Test set accuracy with Feed Forward Neural Network for XOR gate:</span><span style="color: #BB6688; font-weight: bold">{</span>FFNN<span style="color: #666666">.</span>score(X, yXOR)<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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="mathematics-of-deep-learning">Mathematics of deep learning </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Two recent books online</b>
<p>
<ol>
<li> <a href="https://arxiv.org/abs/2105.04026" target="_blank">The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen</a>, published as <a href="https://doi.org/10.1017/9781009025096.002" target="_blank">Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022</a></li>
<li> <a href="https://doi.org/10.48550/arXiv.2310.20360" target="_blank">Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger</a></li>
</ol>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="reminder-on-books-with-hands-on-material-and-codes">Reminder on books with hands-on material and codes </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ul>
<li> <a href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" target="_blank">Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch</a></li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="reading-recommendations">Reading recommendations </h2>
<ol>
<li> Rashkca et al., chapter 11, jupyter-notebook sent separately, from <a href="https://github.com/rasbt/machine-learning-book" target="_blank">GitHub</a></li>
<li> Goodfellow et al, chapter 6 and 7 contain most of the neural network background.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="mathematics-of-deep-learning-and-neural-networks">Mathematics of deep learning and neural networks </h2>
@@ -1269,7 +1016,7 @@ $$
<p>In order to understand the back propagation algorithm and its
derivation (an implementation of the chain rule), let us first digress
with some simple examples. These examples are also meant to motivate
the link with back propagation and <a href="https://en.wikipedia.org/wiki/Automatic_differentiation" target="_blank">automatic differentiation</a>.
the link with back propagation and <a href="https://en.wikipedia.org/wiki/Automatic_differentiation" target="_blank">automatic differentiation</a>. We will discuss these topics next week (week 42).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -1303,7 +1050,9 @@ $$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="automatic-differentiation-through-examples">Automatic differentiation through examples </h2>
<p>A great introduction to automatic differentiation is given by Baydin et al., see <a href="https://arxiv.org/abs/1502.05767" target="_blank"><tt>https://arxiv.org/abs/1502.05767</tt></a>.</p>
<p>A great introduction to automatic differentiation is given by Baydin et al., see <a href="https://arxiv.org/abs/1502.05767" target="_blank"><tt>https://arxiv.org/abs/1502.05767</tt></a>.
See also the video at <a href="https://www.youtube.com/watch?v=wG_nF1awSSY" target="_blank"><tt>https://www.youtube.com/watch?v=wG_nF1awSSY</tt></a>.
</p>
<p>Automatic differentiation is a represented by a repeated application
of the chain rule on well-known functions and allows for the
@@ -2342,487 +2091,9 @@ b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h3 id="activation-functions">Activation functions </h3>
<p>A property that characterizes a neural network, other than its
connectivity, is the choice of activation function(s). As described
in, the following restrictions are imposed on an activation function
for a FFNN to fulfill the universal approximation theorem
</p>
<ul>
<li> Non-constant</li>
<li> Bounded</li>
<li> Monotonically-increasing</li>
<li> Continuous</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h3 id="activation-functions-logistic-and-hyperbolic-ones">Activation functions, Logistic and Hyperbolic ones </h3>
<p>The second requirement excludes all linear functions. Furthermore, in
a MLP with only linear activation functions, each layer simply
performs a linear transformation of its inputs.
</p>
<p>Regardless of the number of layers, the output of the NN will be
nothing but a linear function of the inputs. Thus we need to introduce
some kind of non-linearity to the NN to be able to fit non-linear
functions Typical examples are the logistic <em>Sigmoid</em>
</p>
$$
f(x) = \frac{1}{1 + e^{-x}},
$$
<p>and the <em>hyperbolic tangent</em> function</p>
$$
f(x) = \tanh(x)
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h3 id="relevance">Relevance </h3>
<p>The <em>sigmoid</em> function are more biologically plausible because the
output of inactive neurons are zero. Such activation function are
called <em>one-sided</em>. However, it has been shown that the hyperbolic
tangent performs better than the sigmoid for training MLPs. has
become the most popular for <em>deep neural networks</em>
</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: #BA2121; font-style: italic">&quot;&quot;&quot;The sigmoid function (or the logistic curve) is a </span>
<span style="color: #BA2121; font-style: italic">function that takes any real number, z, and outputs a number (0,1).</span>
<span style="color: #BA2121; font-style: italic">It is useful in neural networks for assigning weights on a relative scale.</span>
<span style="color: #BA2121; font-style: italic">The value z is the weighted sum of parameters involved in the learning algorithm.&quot;&quot;&quot;</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">math</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">mt</span>
z <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>arange(<span style="color: #666666">-5</span>, <span style="color: #666666">5</span>, <span style="color: #666666">.1</span>)
sigma_fn <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>vectorize(<span style="color: #008000; font-weight: bold">lambda</span> z: <span style="color: #666666">1/</span>(<span style="color: #666666">1+</span>numpy<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z)))
sigma <span style="color: #666666">=</span> sigma_fn(z)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot(<span style="color: #666666">111</span>)
ax<span style="color: #666666">.</span>plot(z, sigma)
ax<span style="color: #666666">.</span>set_ylim([<span style="color: #666666">-0.1</span>, <span style="color: #666666">1.1</span>])
ax<span style="color: #666666">.</span>set_xlim([<span style="color: #666666">-5</span>,<span style="color: #666666">5</span>])
ax<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;z&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;sigmoid function&#39;</span>)
plt<span style="color: #666666">.</span>show()
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;Step Function&quot;&quot;&quot;</span>
z <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>arange(<span style="color: #666666">-5</span>, <span style="color: #666666">5</span>, <span style="color: #666666">.02</span>)
step_fn <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>vectorize(<span style="color: #008000; font-weight: bold">lambda</span> z: <span style="color: #666666">1.0</span> <span style="color: #008000; font-weight: bold">if</span> z <span style="color: #666666">&gt;=</span> <span style="color: #666666">0.0</span> <span style="color: #008000; font-weight: bold">else</span> <span style="color: #666666">0.0</span>)
step <span style="color: #666666">=</span> step_fn(z)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot(<span style="color: #666666">111</span>)
ax<span style="color: #666666">.</span>plot(z, step)
ax<span style="color: #666666">.</span>set_ylim([<span style="color: #666666">-0.5</span>, <span style="color: #666666">1.5</span>])
ax<span style="color: #666666">.</span>set_xlim([<span style="color: #666666">-5</span>,<span style="color: #666666">5</span>])
ax<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;z&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;step function&#39;</span>)
plt<span style="color: #666666">.</span>show()
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;Sine Function&quot;&quot;&quot;</span>
z <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>arange(<span style="color: #666666">-2*</span>mt<span style="color: #666666">.</span>pi, <span style="color: #666666">2*</span>mt<span style="color: #666666">.</span>pi, <span style="color: #666666">0.1</span>)
t <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>sin(z)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot(<span style="color: #666666">111</span>)
ax<span style="color: #666666">.</span>plot(z, t)
ax<span style="color: #666666">.</span>set_ylim([<span style="color: #666666">-1.0</span>, <span style="color: #666666">1.0</span>])
ax<span style="color: #666666">.</span>set_xlim([<span style="color: #666666">-2*</span>mt<span style="color: #666666">.</span>pi,<span style="color: #666666">2*</span>mt<span style="color: #666666">.</span>pi])
ax<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;z&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;sine function&#39;</span>)
plt<span style="color: #666666">.</span>show()
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;Plots a graph of the squashing function used by a rectified linear</span>
<span style="color: #BA2121; font-style: italic">unit&quot;&quot;&quot;</span>
z <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>arange(<span style="color: #666666">-2</span>, <span style="color: #666666">2</span>, <span style="color: #666666">.1</span>)
zero <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>zeros(<span style="color: #008000">len</span>(z))
y <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>max([zero, z], axis<span style="color: #666666">=0</span>)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot(<span style="color: #666666">111</span>)
ax<span style="color: #666666">.</span>plot(z, y)
ax<span style="color: #666666">.</span>set_ylim([<span style="color: #666666">-2.0</span>, <span style="color: #666666">2.0</span>])
ax<span style="color: #666666">.</span>set_xlim([<span style="color: #666666">-2.0</span>, <span style="color: #666666">2.0</span>])
ax<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;z&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Rectified linear unit&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="fine-tuning-neural-network-hyperparameters">Fine-tuning neural network hyperparameters </h2>
<p>The flexibility of neural networks is also one of their main
drawbacks: there are many hyperparameters to tweak. Not only can you
use any imaginable network topology (how neurons/nodes are
interconnected), but even in a simple FFNN you can change the number
of layers, the number of neurons per layer, the type of activation
function to use in each layer, the weight initialization logic, the
stochastic gradient optmized and much more. How do you know what
combination of hyperparameters is the best for your task?
</p>
<ul>
<li> You can use grid search with cross-validation to find the right hyperparameters.</li>
</ul>
<p>However,since there are many hyperparameters to tune, and since
training a neural network on a large dataset takes a lot of time, you
will only be able to explore a tiny part of the hyperparameter space.
</p>
<ul>
<li> You can use randomized search.</li>
<li> Or use tools like <a href="http://oscar.calldesk.ai/" target="_blank">Oscar</a>, which implements more complex algorithms to help you find a good set of hyperparameters quickly.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="hidden-layers">Hidden layers </h2>
<p>For many problems you can start with just one or two hidden layers and
it will work just fine. For the MNIST data set you ca easily get a
high accuracy using just one hidden layer with a few hundred neurons.
You can reach for this data set above 98% accuracy using two hidden
layers with the same total amount of neurons, in roughly the same
amount of training time.
</p>
<p>For more complex problems, you can gradually ramp up the number of
hidden layers, until you start overfitting the training set. Very
complex tasks, such as large image classification or speech
recognition, typically require networks with dozens of layers and they
need a huge amount of training data. However, you will rarely have to
train such networks from scratch: it is much more common to reuse
parts of a pretrained state-of-the-art network that performs a similar
task.
</p>
<!-- !split -->
<h2 id="vanishing-gradients">Vanishing gradients </h2>
<p>The Back propagation algorithm we derived above works by going from
the output layer to the input layer, propagating the error gradient on
the way. Once the algorithm has computed the gradient of the cost
function with regards to each parameter in the network, it uses these
gradients to update each parameter with a Gradient Descent (GD) step.
</p>
<p>Unfortunately for us, the gradients often get smaller and smaller as
the algorithm progresses down to the first hidden layers. As a result,
the GD update leaves the lower layer connection weights virtually
unchanged, and training never converges to a good solution. This is
known in the literature as <b>the vanishing gradients problem</b>.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="exploding-gradients">Exploding gradients </h2>
<p>In other cases, the opposite can happen, namely the the gradients can
grow bigger and bigger. The result is that many of the layers get
large updates of the weights the algorithm diverges. This is the
<b>exploding gradients problem</b>, which is mostly encountered in
recurrent neural networks. More generally, deep neural networks suffer
from unstable gradients, different layers may learn at widely
different speeds
</p>
<!-- !split -->
<h2 id="is-the-logistic-activation-function-sigmoid-our-choice">Is the Logistic activation function (Sigmoid) our choice? </h2>
<p>Although this unfortunate behavior has been empirically observed for
quite a while (it was one of the reasons why deep neural networks were
mostly abandoned for a long time), it is only around 2010 that
significant progress was made in understanding it.
</p>
<p>A paper titled <a href="http://proceedings.mlr.press/v9/glorot10a.html" target="_blank">Understanding the Difficulty of Training Deep
Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio</a> found that
the problems with the popular logistic
sigmoid activation function and the weight initialization technique
that was most popular at the time, namely random initialization using
a normal distribution with a mean of 0 and a standard deviation of
1.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="logistic-function-as-the-root-of-problems">Logistic function as the root of problems </h2>
<p>They showed that with this activation function and this
initialization scheme, the variance of the outputs of each layer is
much greater than the variance of its inputs. Going forward in the
network, the variance keeps increasing after each layer until the
activation function saturates at the top layers. This is actually made
worse by the fact that the logistic function has a mean of 0.5, not 0
(the hyperbolic tangent function has a mean of 0 and behaves slightly
better than the logistic function in deep networks).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-derivative-of-the-logistic-funtion">The derivative of the Logistic funtion </h2>
<p>Looking at the logistic activation function, when inputs become large
(negative or positive), the function saturates at 0 or 1, with a
derivative extremely close to 0. Thus when backpropagation kicks in,
it has virtually no gradient to propagate back through the network,
and what little gradient exists keeps getting diluted as
backpropagation progresses down through the top layers, so there is
really nothing left for the lower layers.
</p>
<p>In their paper, Glorot and Bengio propose a way to significantly
alleviate this problem. We need the signal to flow properly in both
directions: in the forward direction when making predictions, and in
the reverse direction when backpropagating gradients. We don&#8217;t want
the signal to die out, nor do we want it to explode and saturate. For
the signal to flow properly, the authors argue that we need the
variance of the outputs of each layer to be equal to the variance of
its inputs, and we also need the gradients to have equal variance
before and after flowing through a layer in the reverse direction.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="insights-from-the-paper-by-glorot-and-bengio">Insights from the paper by Glorot and Bengio </h2>
<p>One of the insights in the 2010 paper by Glorot and Bengio was that
the vanishing/exploding gradients problems were in part due to a poor
choice of activation function. Until then most people had assumed that
if Nature had chosen to use roughly sigmoid activation functions in
biological neurons, they must be an excellent choice. But it turns out
that other activation functions behave much better in deep neural
networks, in particular the ReLU activation function, mostly because
it does not saturate for positive values (and also because it is quite
fast to compute).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-relu-function-family">The RELU function family </h2>
<p>The ReLU activation function suffers from a problem known as the dying
ReLUs: during training, some neurons effectively die, meaning they
stop outputting anything other than 0.
</p>
<p>In some cases, you may find that half of your network&#8217;s neurons are
dead, especially if you used a large learning rate. During training,
if a neuron&#8217;s weights get updated such that the weighted sum of the
neuron&#8217;s inputs is negative, it will start outputting 0. When this
happen, the neuron is unlikely to come back to life since the gradient
of the ReLU function is 0 when its input is negative.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="elu-function">ELU function </h2>
<p>To solve this problem, nowadays practitioners use a variant of the
ReLU function, such as the leaky ReLU discussed above or the so-called
exponential linear unit (ELU) function
</p>
$$
ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="which-activation-function-should-we-use">Which activation function should we use? </h2>
<p>In general it seems that the ELU activation function is better than
the leaky ReLU function (and its variants), which is better than
ReLU. ReLU performs better than \( \tanh \) which in turn performs better
than the logistic function.
</p>
<p>If runtime performance is an issue, then you may opt for the leaky
ReLU function over the ELU function If you don&#8217;t want to tweak yet
another hyperparameter, you may just use the default \( \alpha \) of
\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and
computing power, you can use cross-validation or bootstrap to evaluate
other activation functions.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-on-activation-functions-output-layers">More on activation functions, output layers </h2>
<p>In most cases you can use the ReLU activation function in the hidden
layers (or one of its variants).
</p>
<p>It is a bit faster to compute than other activation functions, and the
gradient descent optimization does in general not get stuck.
</p>
<b>For the output layer:</b>
<ul>
<li> For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).</li>
<li> For regression tasks, you can simply use no activation function at all.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="batch-normalization">Batch Normalization </h2>
<p>Batch Normalization aims to address the vanishing/exploding gradients
problems, and more generally the problem that the distribution of each
layer&#8217;s inputs changes during training, as the parameters of the
previous layers change.
</p>
<p>The technique consists of adding an operation in the model just before
the activation function of each layer, simply zero-centering and
normalizing the inputs, then scaling and shifting the result using two
new parameters per layer (one for scaling, the other for shifting). In
other words, this operation lets the model learn the optimal scale and
mean of the inputs for each layer. In order to zero-center and
normalize the inputs, the algorithm needs to estimate the inputs&#8217; mean
and standard deviation. It does so by evaluating the mean and standard
deviation of the inputs over the current mini-batch, from this the
name batch normalization.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="dropout">Dropout </h2>
<p>It is a fairly simple algorithm: at every training step, every neuron
(including the input neurons but excluding the output neurons) has a
probability \( p \) of being temporarily dropped out, meaning it will be
entirely ignored during this training step, but it may be active
during the next step.
</p>
<p>The hyperparameter \( p \) is called the dropout rate, and it is typically
set to 50%. After training, the neurons are not dropped anymore. It
is viewed as one of the most popular regularization techniques.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="gradient-clipping">Gradient Clipping </h2>
<p>A popular technique to lessen the exploding gradients problem is to
simply clip the gradients during backpropagation so that they never
exceed some threshold (this is mostly useful for recurrent neural
networks).
</p>
<p>This technique is called Gradient Clipping.</p>
<p>In general however, Batch
Normalization is preferred.
</p>
<!-- !split -->
<h2 id="a-top-down-perspective-on-neural-networks">A top-down perspective on Neural networks </h2>
<p>The first thing we would like to do is divide the data into two or
three parts. A training set, a validation or dev (development) set,
and a test set. The test set is the data on which we want to make
predictions. The dev set is a subset of the training data we use to
check how well we are doing out-of-sample, after training the model on
the training dataset. We use the validation error as a proxy for the
test error in order to make tweaks to our model. It is crucial that we
do not use any of the test data to train the algorithm. This is a
cardinal sin in ML. Then:
</p>
<ol>
<li> Estimate optimal error rate</li>
<li> Minimize underfitting (bias) on training data set.</li>
<li> Make sure you are not overfitting.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-top-down-perspectives">More top-down perspectives </h2>
<p>If the validation and test sets are drawn from the same distributions,
then a good performance on the validation set should lead to similarly
good performance on the test set.
</p>
<p>However, sometimes
the training data and test data differ in subtle ways because, for
example, they are collected using slightly different methods, or
because it is cheaper to collect data in one way versus another. In
this case, there can be a mismatch between the training and test
data. This can lead to the neural network overfitting these small
differences between the test and training sets, and a poor performance
on the test set despite having a good performance on the validation
set. To rectify this, Andrew Ng suggests making two validation or dev
sets, one constructed from the training data and one constructed from
the test data. The difference between the performance of the algorithm
on these two validation sets quantifies the train-test mismatch. This
can serve as another important diagnostic when using DNNs for
supervised learning.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="limitations-of-supervised-learning-with-deep-networks">Limitations of supervised learning with deep networks </h2>
<p>Like all statistical methods, supervised learning using neural
networks has important limitations. This is especially important when
one seeks to apply these methods, especially to physics problems. Like
all tools, DNNs are not a universal solution. Often, the same or
better performance on a task can be achieved by using a few
hand-engineered features (or even a collection of random
features).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="limitations-of-nns">Limitations of NNs </h2>
<p>Here we list some of the important limitations of supervised neural network based models. </p>
<ul>
<li> <b>Need labeled data</b>. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).</li>
<li> <b>Supervised neural networks are extremely data intensive.</b> DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="homogeneous-data">Homogeneous data </h2>
<ul>
<li> <b>Homogeneous data.</b> Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e.&nbsp;some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-limitations">More limitations </h2>
<ul>
<li> <b>Many problems are not about prediction.</b> In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a <em>wrong</em> model. The model might or might not be useful for understanding the underlying science.</li>
</ul>
<p>Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.</p>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
<!-- copyright --> &copy; 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>
Binary file not shown.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,11 @@
\begin{MintedVerbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}]
\PYG{k+kn}{from}\PYG{+w}{ }\PYG{n+nn}{\PYGZus{}\PYGZus{}future\PYGZus{}\PYGZus{}}\PYG{+w}{ }\PYG{k+kn}{import} \PYG{n}{division}
\PYG{k+kn}{from}\PYG{+w}{ }\PYG{n+nn}{sympy}\PYG{+w}{ }\PYG{k+kn}{import} \PYG{o}{*}
\PYG{n}{x} \PYG{o}{=} \PYG{n}{symbols}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{x}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)}
\PYG{n}{expr} \PYG{o}{=} \PYG{n}{sqrt}\PYG{p}{(}\PYG{n}{x}\PYG{o}{*}\PYG{n}{x}\PYG{o}{+}\PYG{n}{exp}\PYG{p}{(}\PYG{n}{x}\PYG{o}{*}\PYG{n}{x}\PYG{p}{)}\PYG{p}{)}
\PYG{n}{simplify}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{)}
\PYG{n}{derivative} \PYG{o}{=} \PYG{n}{diff}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{,}\PYG{n}{x}\PYG{p}{)}
\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{python}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{)}\PYG{p}{)}
\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{python}\PYG{p}{(}\PYG{n}{derivative}\PYG{p}{)}\PYG{p}{)}
\end{MintedVerbatim}
@@ -0,0 +1,67 @@
\begin{MintedVerbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}]
\PYG{k+kn}{import}\PYG{+w}{ }\PYG{n+nn}{numpy}\PYG{+w}{ }\PYG{k}{as}\PYG{+w}{ }\PYG{n+nn}{np}
\PYG{c+c1}{\PYGZsh{} We use the Sigmoid function as activation function}
\PYG{k}{def}\PYG{+w}{ }\PYG{n+nf}{sigmoid}\PYG{p}{(}\PYG{n}{z}\PYG{p}{)}\PYG{p}{:}
\PYG{k}{return} \PYG{l+m+mf}{1.0}\PYG{o}{/}\PYG{p}{(}\PYG{l+m+mf}{1.0}\PYG{o}{+}\PYG{n}{np}\PYG{o}{.}\PYG{n}{exp}\PYG{p}{(}\PYG{o}{\PYGZhy{}}\PYG{n}{z}\PYG{p}{)}\PYG{p}{)}
\PYG{k}{def}\PYG{+w}{ }\PYG{n+nf}{forwardpropagation}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{:}
\PYG{c+c1}{\PYGZsh{} weighted sum of inputs to the hidden layer}
\PYG{n}{z\PYGZus{}1} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{x}\PYG{p}{,} \PYG{n}{w\PYGZus{}1}\PYG{p}{)} \PYG{o}{+} \PYG{n}{b\PYGZus{}1}
\PYG{c+c1}{\PYGZsh{} activation in the hidden layer}
\PYG{n}{a\PYGZus{}1} \PYG{o}{=} \PYG{n}{sigmoid}\PYG{p}{(}\PYG{n}{z\PYGZus{}1}\PYG{p}{)}
\PYG{c+c1}{\PYGZsh{} weighted sum of inputs to the output layer}
\PYG{n}{z\PYGZus{}2} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{a\PYGZus{}1}\PYG{p}{,} \PYG{n}{w\PYGZus{}2}\PYG{p}{)} \PYG{o}{+} \PYG{n}{b\PYGZus{}2}
\PYG{n}{a\PYGZus{}2} \PYG{o}{=} \PYG{n}{z\PYGZus{}2}
\PYG{k}{return} \PYG{n}{a\PYGZus{}1}\PYG{p}{,} \PYG{n}{a\PYGZus{}2}
\PYG{k}{def}\PYG{+w}{ }\PYG{n+nf}{backpropagation}\PYG{p}{(}\PYG{n}{x}\PYG{p}{,} \PYG{n}{y}\PYG{p}{)}\PYG{p}{:}
\PYG{n}{a\PYGZus{}1}\PYG{p}{,} \PYG{n}{a\PYGZus{}2} \PYG{o}{=} \PYG{n}{forwardpropagation}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}
\PYG{c+c1}{\PYGZsh{} parameter delta for the output layer, note that a\PYGZus{}2=z\PYGZus{}2 and its derivative wrt z\PYGZus{}2 is just 1}
\PYG{n}{delta\PYGZus{}2} \PYG{o}{=} \PYG{n}{a\PYGZus{}2} \PYG{o}{\PYGZhy{}} \PYG{n}{y}
\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+m+mf}{0.5}\PYG{o}{*}\PYG{p}{(}\PYG{p}{(}\PYG{n}{a\PYGZus{}2}\PYG{o}{\PYGZhy{}}\PYG{n}{y}\PYG{p}{)}\PYG{o}{*}\PYG{o}{*}\PYG{l+m+mi}{2}\PYG{p}{)}\PYG{p}{)}
\PYG{c+c1}{\PYGZsh{} delta for the hidden layer}
\PYG{n}{delta\PYGZus{}1} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{delta\PYGZus{}2}\PYG{p}{,} \PYG{n}{w\PYGZus{}2}\PYG{o}{.}\PYG{n}{T}\PYG{p}{)} \PYG{o}{*} \PYG{n}{a\PYGZus{}1} \PYG{o}{*} \PYG{p}{(}\PYG{l+m+mi}{1} \PYG{o}{\PYGZhy{}} \PYG{n}{a\PYGZus{}1}\PYG{p}{)}
\PYG{c+c1}{\PYGZsh{} gradients for the output layer}
\PYG{n}{output\PYGZus{}weights\PYGZus{}gradient} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{a\PYGZus{}1}\PYG{o}{.}\PYG{n}{T}\PYG{p}{,} \PYG{n}{delta\PYGZus{}2}\PYG{p}{)}
\PYG{n}{output\PYGZus{}bias\PYGZus{}gradient} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{sum}\PYG{p}{(}\PYG{n}{delta\PYGZus{}2}\PYG{p}{,} \PYG{n}{axis}\PYG{o}{=}\PYG{l+m+mi}{0}\PYG{p}{)}
\PYG{c+c1}{\PYGZsh{} gradient for the hidden layer}
\PYG{n}{hidden\PYGZus{}weights\PYGZus{}gradient} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{x}\PYG{o}{.}\PYG{n}{T}\PYG{p}{,} \PYG{n}{delta\PYGZus{}1}\PYG{p}{)}
\PYG{n}{hidden\PYGZus{}bias\PYGZus{}gradient} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{sum}\PYG{p}{(}\PYG{n}{delta\PYGZus{}1}\PYG{p}{,} \PYG{n}{axis}\PYG{o}{=}\PYG{l+m+mi}{0}\PYG{p}{)}
\PYG{k}{return} \PYG{n}{output\PYGZus{}weights\PYGZus{}gradient}\PYG{p}{,} \PYG{n}{output\PYGZus{}bias\PYGZus{}gradient}\PYG{p}{,} \PYG{n}{hidden\PYGZus{}weights\PYGZus{}gradient}\PYG{p}{,} \PYG{n}{hidden\PYGZus{}bias\PYGZus{}gradient}
\PYG{c+c1}{\PYGZsh{} ensure the same random numbers appear every time}
\PYG{n}{np}\PYG{o}{.}\PYG{n}{random}\PYG{o}{.}\PYG{n}{seed}\PYG{p}{(}\PYG{l+m+mi}{0}\PYG{p}{)}
\PYG{c+c1}{\PYGZsh{} Input variable}
\PYG{n}{x} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{(}\PYG{p}{[}\PYG{l+m+mf}{4.0}\PYG{p}{]}\PYG{p}{,}\PYG{n}{dtype}\PYG{o}{=}\PYG{n}{np}\PYG{o}{.}\PYG{n}{float64}\PYG{p}{)}
\PYG{c+c1}{\PYGZsh{} Target values}
\PYG{n}{y} \PYG{o}{=} \PYG{l+m+mi}{2}\PYG{o}{*}\PYG{n}{x}\PYG{o}{+}\PYG{l+m+mf}{1.0}
\PYG{c+c1}{\PYGZsh{} Defining the neural network, only scalars here}
\PYG{n}{n\PYGZus{}inputs} \PYG{o}{=} \PYG{n}{x}\PYG{o}{.}\PYG{n}{shape}
\PYG{n}{n\PYGZus{}features} \PYG{o}{=} \PYG{l+m+mi}{1}
\PYG{n}{n\PYGZus{}hidden\PYGZus{}neurons} \PYG{o}{=} \PYG{l+m+mi}{1}
\PYG{n}{n\PYGZus{}outputs} \PYG{o}{=} \PYG{l+m+mi}{1}
\PYG{c+c1}{\PYGZsh{} Initialize the network}
\PYG{c+c1}{\PYGZsh{} weights and bias in the hidden layer}
\PYG{n}{w\PYGZus{}1} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{random}\PYG{o}{.}\PYG{n}{randn}\PYG{p}{(}\PYG{n}{n\PYGZus{}features}\PYG{p}{,} \PYG{n}{n\PYGZus{}hidden\PYGZus{}neurons}\PYG{p}{)}
\PYG{n}{b\PYGZus{}1} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{zeros}\PYG{p}{(}\PYG{n}{n\PYGZus{}hidden\PYGZus{}neurons}\PYG{p}{)} \PYG{o}{+} \PYG{l+m+mf}{0.01}
\PYG{c+c1}{\PYGZsh{} weights and bias in the output layer}
\PYG{n}{w\PYGZus{}2} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{random}\PYG{o}{.}\PYG{n}{randn}\PYG{p}{(}\PYG{n}{n\PYGZus{}hidden\PYGZus{}neurons}\PYG{p}{,} \PYG{n}{n\PYGZus{}outputs}\PYG{p}{)}
\PYG{n}{b\PYGZus{}2} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{zeros}\PYG{p}{(}\PYG{n}{n\PYGZus{}outputs}\PYG{p}{)} \PYG{o}{+} \PYG{l+m+mf}{0.01}
\PYG{n}{eta} \PYG{o}{=} \PYG{l+m+mf}{0.1}
\PYG{k}{for} \PYG{n}{i} \PYG{o+ow}{in} \PYG{n+nb}{range}\PYG{p}{(}\PYG{l+m+mi}{50}\PYG{p}{)}\PYG{p}{:}
\PYG{c+c1}{\PYGZsh{} calculate gradients}
\PYG{n}{derivW2}\PYG{p}{,} \PYG{n}{derivB2}\PYG{p}{,} \PYG{n}{derivW1}\PYG{p}{,} \PYG{n}{derivB1} \PYG{o}{=} \PYG{n}{backpropagation}\PYG{p}{(}\PYG{n}{x}\PYG{p}{,} \PYG{n}{y}\PYG{p}{)}
\PYG{c+c1}{\PYGZsh{} update weights and biases}
\PYG{n}{w\PYGZus{}2} \PYG{o}{\PYGZhy{}}\PYG{o}{=} \PYG{n}{eta} \PYG{o}{*} \PYG{n}{derivW2}
\PYG{n}{b\PYGZus{}2} \PYG{o}{\PYGZhy{}}\PYG{o}{=} \PYG{n}{eta} \PYG{o}{*} \PYG{n}{derivB2}
\PYG{n}{w\PYGZus{}1} \PYG{o}{\PYGZhy{}}\PYG{o}{=} \PYG{n}{eta} \PYG{o}{*} \PYG{n}{derivW1}
\PYG{n}{b\PYGZus{}1} \PYG{o}{\PYGZhy{}}\PYG{o}{=} \PYG{n}{eta} \PYG{o}{*} \PYG{n}{derivB1}
\end{MintedVerbatim}
@@ -0,0 +1,11 @@
\begin{MintedVerbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}]
\PYG{k+kn}{from}\PYG{+w}{ }\PYG{n+nn}{\PYGZus{}\PYGZus{}future\PYGZus{}\PYGZus{}}\PYG{+w}{ }\PYG{k+kn}{import} \PYG{n}{division}
\PYG{k+kn}{from}\PYG{+w}{ }\PYG{n+nn}{sympy}\PYG{+w}{ }\PYG{k+kn}{import} \PYG{o}{*}
\PYG{n}{x} \PYG{o}{=} \PYG{n}{symbols}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{x}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)}
\PYG{n}{expr} \PYG{o}{=} \PYG{n}{exp}\PYG{p}{(}\PYG{n}{x}\PYG{o}{*}\PYG{n}{x}\PYG{p}{)}
\PYG{n}{simplify}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{)}
\PYG{n}{derivative} \PYG{o}{=} \PYG{n}{diff}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{,}\PYG{n}{x}\PYG{p}{)}
\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{python}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{)}\PYG{p}{)}
\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{python}\PYG{p}{(}\PYG{n}{derivative}\PYG{p}{)}\PYG{p}{)}
\end{MintedVerbatim}
@@ -0,0 +1,12 @@
{
"jobname": "week41",
"md5": "F65A394E8F693820B1C98E9CDA6B0A8F",
"timestamp": "20251005194057",
"cachefiles": [
"65E03FF20B6B3DC1E8F8756667419FF9.highlight.minted",
"93B9C4D3B722A5D46E6B643B143D1A87.highlight.minted",
"FCC7426E301CBCF11A668C5057AF3D1A.highlight.minted",
"_F65A394E8F693820B1C98E9CDA6B0A8F.index.minted",
"default.style.minted"
]
}
+100
View File
@@ -0,0 +1,100 @@
\makeatletter
\def\PYG@reset{\let\PYG@it=\relax \let\PYG@bf=\relax%
\let\PYG@ul=\relax \let\PYG@tc=\relax%
\let\PYG@bc=\relax \let\PYG@ff=\relax}
\def\PYG@tok#1{\csname PYG@tok@#1\endcsname}
\def\PYG@toks#1+{\ifx\relax#1\empty\else%
\PYG@tok{#1}\expandafter\PYG@toks\fi}
\def\PYG@do#1{\PYG@bc{\PYG@tc{\PYG@ul{%
\PYG@it{\PYG@bf{\PYG@ff{#1}}}}}}}
\def\PYG#1#2{\PYG@reset\PYG@toks#1+\relax+\PYG@do{#2}}
\@namedef{PYG@tok@w}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.73,0.73}{##1}}}
\@namedef{PYG@tok@c}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}}
\@namedef{PYG@tok@cp}{\def\PYG@tc##1{\textcolor[rgb]{0.61,0.40,0.00}{##1}}}
\@namedef{PYG@tok@k}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@kp}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@kt}{\def\PYG@tc##1{\textcolor[rgb]{0.69,0.00,0.25}{##1}}}
\@namedef{PYG@tok@o}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\@namedef{PYG@tok@ow}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}}
\@namedef{PYG@tok@nb}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@nf}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
\@namedef{PYG@tok@nc}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
\@namedef{PYG@tok@nn}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
\@namedef{PYG@tok@ne}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.80,0.25,0.22}{##1}}}
\@namedef{PYG@tok@nv}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
\@namedef{PYG@tok@no}{\def\PYG@tc##1{\textcolor[rgb]{0.53,0.00,0.00}{##1}}}
\@namedef{PYG@tok@nl}{\def\PYG@tc##1{\textcolor[rgb]{0.46,0.46,0.00}{##1}}}
\@namedef{PYG@tok@ni}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.44,0.44,0.44}{##1}}}
\@namedef{PYG@tok@na}{\def\PYG@tc##1{\textcolor[rgb]{0.41,0.47,0.13}{##1}}}
\@namedef{PYG@tok@nt}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@nd}{\def\PYG@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}}
\@namedef{PYG@tok@s}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
\@namedef{PYG@tok@sd}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
\@namedef{PYG@tok@si}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.64,0.35,0.47}{##1}}}
\@namedef{PYG@tok@se}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.67,0.36,0.12}{##1}}}
\@namedef{PYG@tok@sr}{\def\PYG@tc##1{\textcolor[rgb]{0.64,0.35,0.47}{##1}}}
\@namedef{PYG@tok@ss}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
\@namedef{PYG@tok@sx}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@m}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\@namedef{PYG@tok@gh}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}
\@namedef{PYG@tok@gu}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.50,0.00,0.50}{##1}}}
\@namedef{PYG@tok@gd}{\def\PYG@tc##1{\textcolor[rgb]{0.63,0.00,0.00}{##1}}}
\@namedef{PYG@tok@gi}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.52,0.00}{##1}}}
\@namedef{PYG@tok@gr}{\def\PYG@tc##1{\textcolor[rgb]{0.89,0.00,0.00}{##1}}}
\@namedef{PYG@tok@ge}{\let\PYG@it=\textit}
\@namedef{PYG@tok@gs}{\let\PYG@bf=\textbf}
\@namedef{PYG@tok@ges}{\let\PYG@bf=\textbf\let\PYG@it=\textit}
\@namedef{PYG@tok@gp}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}
\@namedef{PYG@tok@go}{\def\PYG@tc##1{\textcolor[rgb]{0.44,0.44,0.44}{##1}}}
\@namedef{PYG@tok@gt}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.27,0.87}{##1}}}
\@namedef{PYG@tok@err}{\def\PYG@bc##1{{\setlength{\fboxsep}{\string -\fboxrule}\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}}
\@namedef{PYG@tok@kc}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@kd}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@kn}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@kr}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@bp}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
\@namedef{PYG@tok@fm}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
\@namedef{PYG@tok@vc}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
\@namedef{PYG@tok@vg}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
\@namedef{PYG@tok@vi}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
\@namedef{PYG@tok@vm}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
\@namedef{PYG@tok@sa}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
\@namedef{PYG@tok@sb}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
\@namedef{PYG@tok@sc}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
\@namedef{PYG@tok@dl}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
\@namedef{PYG@tok@s2}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
\@namedef{PYG@tok@sh}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
\@namedef{PYG@tok@s1}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
\@namedef{PYG@tok@mb}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\@namedef{PYG@tok@mf}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\@namedef{PYG@tok@mh}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\@namedef{PYG@tok@mi}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\@namedef{PYG@tok@il}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\@namedef{PYG@tok@mo}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\@namedef{PYG@tok@ch}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}}
\@namedef{PYG@tok@cm}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}}
\@namedef{PYG@tok@cpf}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}}
\@namedef{PYG@tok@c1}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}}
\@namedef{PYG@tok@cs}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}}
\def\PYGZbs{\char`\\}
\def\PYGZus{\char`\_}
\def\PYGZob{\char`\{}
\def\PYGZcb{\char`\}}
\def\PYGZca{\char`\^}
\def\PYGZam{\char`\&}
\def\PYGZlt{\char`\<}
\def\PYGZgt{\char`\>}
\def\PYGZsh{\char`\#}
\def\PYGZpc{\char`\%}
\def\PYGZdl{\char`\$}
\def\PYGZhy{\char`\-}
\def\PYGZsq{\char`\'}
\def\PYGZdq{\char`\"}
\def\PYGZti{\char`\~}
% for compatibility with earlier versions
\def\PYGZat{@}
\def\PYGZlb{[}
\def\PYGZrb{]}
\makeatother
Binary file not shown.
+24 -613
View File
@@ -9,13 +9,13 @@ DATE: Week 41
!split
===== Material for the lecture on Monday October 6, 2025 =====
o Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
o Building our own Feed-forward Neural Network
o Building our own Feed-forward Neural Network, getting started
# * Video of lecture notes at URL:"https://youtu.be/pMRUbf9E-gM"
# * Whiteboard notes at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf"
!bblock Readings and Videos:
o These lecture notes
o Rashcka et al chapter 11
o For neural networks we recommend Goodfellow et al chapter 6.
o For neural networks we recommend Goodfellow et al chapters 6 and 7.
o Rashkca et al., chapter 11, jupyter-notebook sent separately, from "GitHub":"https://github.com/rasbt/machine-learning-book"
o Neural Networks demystified at URL:"https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs"
o Building Neural Networks from scratch at URL:"https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex"
o Video on Neural Networks at URL:"https://www.youtube.com/watch?v=CqOfi41LfDw"
@@ -23,13 +23,27 @@ o Video on the back propagation algorithm at URL:"https://www.youtube.com/watch?
We also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at URL:"http://neuralnetworksanddeeplearning.com/chap4.html".
!eblock
!split
===== Mathematics of deep learning =====
!bblock Two recent books online
o "The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen":"https://arxiv.org/abs/2105.04026", published as "Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022":"https://doi.org/10.1017/9781009025096.002"
o "Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger":"https://doi.org/10.48550/arXiv.2310.20360"
!eblock
!split
===== Material for the active learning sessions on Tuesday and Wednesday =====
* Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation
* One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code
* Discussion of project 2
* Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent
===== Reminder on books with hands-on material and codes =====
!bblock
* "Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch":"https://sebastianraschka.com/blog/2022/ml-pytorch-book.html"
!eblock
!split
===== Lab sessions on Tuesday and Wednesday =====
o Getting started with coding neural network. The exercises this week aim at setting up the feed-forward part of a neural network.
@@ -221,153 +235,8 @@ as to not restrict the range of output values.
FIGURE: [figures/nns.png, width=600 frac=0.8] In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.
!split
===== Examples of XOR, OR and AND gates =====
Let us first try to fit various gates using standard linear
regression. The gates we are thinking of are the classical XOR, OR and
AND gates, well-known elements in computer science. The tables here
show how we can set up the inputs $x_1$ and $x_2$ in order to yield a
specific target $y_i$.
!bc pycod
"""
Simple code that tests XOR, OR and AND gates with linear regression
"""
import numpy as np
# Design matrix
X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
print(f"The X.TX matrix:{X.T @ X}")
Xinv = np.linalg.pinv(X.T @ X)
print(f"The invers of X.TX matrix:{Xinv}")
# The XOR gate
yXOR = np.array( [ 0, 1 ,1, 0])
ThetaXOR = Xinv @ X.T @ yXOR
print(f"The values of theta for the XOR gate:{ThetaXOR}")
print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}")
# The OR gate
yOR = np.array( [ 0, 1 ,1, 1])
ThetaOR = Xinv @ X.T @ yOR
print(f"The values of theta for the OR gate:{ThetaOR}")
print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}")
# The OR gate
yAND = np.array( [ 0, 0 ,0, 1])
ThetaAND = Xinv @ X.T @ yAND
print(f"The values of theta for the AND gate:{ThetaAND}")
print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}")
!ec
What is happening here?
!split
===== Does Logistic Regression do a better Job? =====
!bc pycod
"""
Simple code that tests XOR and OR gates with linear regression
and logistic regression
"""
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
import numpy as np
# Design matrix
X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
print(f"The X.TX matrix:{X.T @ X}")
Xinv = np.linalg.pinv(X.T @ X)
print(f"The invers of X.TX matrix:{Xinv}")
# The XOR gate
yXOR = np.array( [ 0, 1 ,1, 0])
ThetaXOR = Xinv @ X.T @ yXOR
print(f"The values of theta for the XOR gate:{ThetaXOR}")
print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}")
# The OR gate
yOR = np.array( [ 0, 1 ,1, 1])
ThetaOR = Xinv @ X.T @ yOR
print(f"The values of theta for the OR gate:{ThetaOR}")
print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}")
# The OR gate
yAND = np.array( [ 0, 0 ,0, 1])
ThetaAND = Xinv @ X.T @ yAND
print(f"The values of theta for the AND gate:{ThetaAND}")
print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}")
# Now we change to logistic regression
# Logistic Regression
logreg = LogisticRegression()
logreg.fit(X, yOR)
print("Test set accuracy with Logistic Regression for OR gate: {:.2f}".format(logreg.score(X,yOR)))
logreg.fit(X, yXOR)
print("Test set accuracy with Logistic Regression for XOR gate: {:.2f}".format(logreg.score(X,yXOR)))
logreg.fit(X, yAND)
print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND)))
!ec
Not exactly impressive, but somewhat better.
!split
===== Adding Neural Networks =====
!bc pycod
# and now neural networks with Scikit-Learn and the XOR
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import make_classification
X, yXOR = make_classification(n_samples=100, random_state=1)
FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)
FFNN.predict_proba(X)
print(f"Test set accuracy with Feed Forward Neural Network for XOR gate:{FFNN.score(X, yXOR)}")
!ec
!split
===== Mathematics of deep learning =====
!bblock Two recent books online
o "The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen":"https://arxiv.org/abs/2105.04026", published as "Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022":"https://doi.org/10.1017/9781009025096.002"
o "Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger":"https://doi.org/10.48550/arXiv.2310.20360"
!eblock
!split
===== Reminder on books with hands-on material and codes =====
!bblock
* "Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch":"https://sebastianraschka.com/blog/2022/ml-pytorch-book.html"
!eblock
!split
===== Reading recommendations =====
o Rashkca et al., chapter 11, jupyter-notebook sent separately, from "GitHub":"https://github.com/rasbt/machine-learning-book"
o Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
!split
===== Mathematics of deep learning and neural networks =====
@@ -677,7 +546,7 @@ The last partial derivative can easily be computed and reads (by applying the ch
In order to understand the back propagation algorithm and its
derivation (an implementation of the chain rule), let us first digress
with some simple examples. These examples are also meant to motivate
the link with back propagation and "automatic differentiation":"https://en.wikipedia.org/wiki/Automatic_differentiation".
the link with back propagation and "automatic differentiation":"https://en.wikipedia.org/wiki/Automatic_differentiation". We will discuss these topics next week (week 42).
!split
===== Reminder on the chain rule and gradients =====
@@ -719,6 +588,7 @@ the gradient of $f$ with respect to $t$ and $s$ (without the explicit unit vecto
===== Automatic differentiation through examples =====
A great introduction to automatic differentiation is given by Baydin et al., see URL:"https://arxiv.org/abs/1502.05767".
See also the video at URL:"https://www.youtube.com/watch?v=wG_nF1awSSY".
Automatic differentiation is a represented by a repeated application
of the chain rule on well-known functions and allows for the
@@ -1778,462 +1648,3 @@ b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta
!split
=== Activation functions ===
A property that characterizes a neural network, other than its
connectivity, is the choice of activation function(s). As described
in, the following restrictions are imposed on an activation function
for a FFNN to fulfill the universal approximation theorem
* Non-constant
* Bounded
* Monotonically-increasing
* Continuous
!split
=== Activation functions, Logistic and Hyperbolic ones ===
The second requirement excludes all linear functions. Furthermore, in
a MLP with only linear activation functions, each layer simply
performs a linear transformation of its inputs.
Regardless of the number of layers, the output of the NN will be
nothing but a linear function of the inputs. Thus we need to introduce
some kind of non-linearity to the NN to be able to fit non-linear
functions Typical examples are the logistic *Sigmoid*
!bt
\[
f(x) = \frac{1}{1 + e^{-x}},
\]
!et
and the *hyperbolic tangent* function
!bt
\[
f(x) = \tanh(x)
\]
!et
!split
=== Relevance ===
The *sigmoid* function are more biologically plausible because the
output of inactive neurons are zero. Such activation function are
called *one-sided*. However, it has been shown that the hyperbolic
tangent performs better than the sigmoid for training MLPs. has
become the most popular for *deep neural networks*
!bc pycod
"""The sigmoid function (or the logistic curve) is a
function that takes any real number, z, and outputs a number (0,1).
It is useful in neural networks for assigning weights on a relative scale.
The value z is the weighted sum of parameters involved in the learning algorithm."""
import numpy
import matplotlib.pyplot as plt
import math as mt
z = numpy.arange(-5, 5, .1)
sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
sigma = sigma_fn(z)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, sigma)
ax.set_ylim([-0.1, 1.1])
ax.set_xlim([-5,5])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('sigmoid function')
plt.show()
"""Step Function"""
z = numpy.arange(-5, 5, .02)
step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
step = step_fn(z)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, step)
ax.set_ylim([-0.5, 1.5])
ax.set_xlim([-5,5])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('step function')
plt.show()
"""Sine Function"""
z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
t = numpy.sin(z)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, t)
ax.set_ylim([-1.0, 1.0])
ax.set_xlim([-2*mt.pi,2*mt.pi])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('sine function')
plt.show()
"""Plots a graph of the squashing function used by a rectified linear
unit"""
z = numpy.arange(-2, 2, .1)
zero = numpy.zeros(len(z))
y = numpy.max([zero, z], axis=0)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, y)
ax.set_ylim([-2.0, 2.0])
ax.set_xlim([-2.0, 2.0])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('Rectified linear unit')
plt.show()
!ec
!split
===== Fine-tuning neural network hyperparameters =====
The flexibility of neural networks is also one of their main
drawbacks: there are many hyperparameters to tweak. Not only can you
use any imaginable network topology (how neurons/nodes are
interconnected), but even in a simple FFNN you can change the number
of layers, the number of neurons per layer, the type of activation
function to use in each layer, the weight initialization logic, the
stochastic gradient optmized and much more. How do you know what
combination of hyperparameters is the best for your task?
* You can use grid search with cross-validation to find the right hyperparameters.
However,since there are many hyperparameters to tune, and since
training a neural network on a large dataset takes a lot of time, you
will only be able to explore a tiny part of the hyperparameter space.
* You can use randomized search.
* Or use tools like "Oscar":"http://oscar.calldesk.ai/", which implements more complex algorithms to help you find a good set of hyperparameters quickly.
!split
===== Hidden layers =====
For many problems you can start with just one or two hidden layers and
it will work just fine. For the MNIST data set you ca easily get a
high accuracy using just one hidden layer with a few hundred neurons.
You can reach for this data set above 98% accuracy using two hidden
layers with the same total amount of neurons, in roughly the same
amount of training time.
For more complex problems, you can gradually ramp up the number of
hidden layers, until you start overfitting the training set. Very
complex tasks, such as large image classification or speech
recognition, typically require networks with dozens of layers and they
need a huge amount of training data. However, you will rarely have to
train such networks from scratch: it is much more common to reuse
parts of a pretrained state-of-the-art network that performs a similar
task.
!split
===== Vanishing gradients =====
The Back propagation algorithm we derived above works by going from
the output layer to the input layer, propagating the error gradient on
the way. Once the algorithm has computed the gradient of the cost
function with regards to each parameter in the network, it uses these
gradients to update each parameter with a Gradient Descent (GD) step.
Unfortunately for us, the gradients often get smaller and smaller as
the algorithm progresses down to the first hidden layers. As a result,
the GD update leaves the lower layer connection weights virtually
unchanged, and training never converges to a good solution. This is
known in the literature as _the vanishing gradients problem_.
!split
===== Exploding gradients =====
In other cases, the opposite can happen, namely the the gradients can
grow bigger and bigger. The result is that many of the layers get
large updates of the weights the algorithm diverges. This is the
_exploding gradients problem_, which is mostly encountered in
recurrent neural networks. More generally, deep neural networks suffer
from unstable gradients, different layers may learn at widely
different speeds
!split
===== Is the Logistic activation function (Sigmoid) our choice? =====
Although this unfortunate behavior has been empirically observed for
quite a while (it was one of the reasons why deep neural networks were
mostly abandoned for a long time), it is only around 2010 that
significant progress was made in understanding it.
A paper titled "Understanding the Difficulty of Training Deep
Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio":"http://proceedings.mlr.press/v9/glorot10a.html" found that
the problems with the popular logistic
sigmoid activation function and the weight initialization technique
that was most popular at the time, namely random initialization using
a normal distribution with a mean of 0 and a standard deviation of
1.
!split
===== Logistic function as the root of problems =====
They showed that with this activation function and this
initialization scheme, the variance of the outputs of each layer is
much greater than the variance of its inputs. Going forward in the
network, the variance keeps increasing after each layer until the
activation function saturates at the top layers. This is actually made
worse by the fact that the logistic function has a mean of 0.5, not 0
(the hyperbolic tangent function has a mean of 0 and behaves slightly
better than the logistic function in deep networks).
!split
===== The derivative of the Logistic funtion =====
Looking at the logistic activation function, when inputs become large
(negative or positive), the function saturates at 0 or 1, with a
derivative extremely close to 0. Thus when backpropagation kicks in,
it has virtually no gradient to propagate back through the network,
and what little gradient exists keeps getting diluted as
backpropagation progresses down through the top layers, so there is
really nothing left for the lower layers.
In their paper, Glorot and Bengio propose a way to significantly
alleviate this problem. We need the signal to flow properly in both
directions: in the forward direction when making predictions, and in
the reverse direction when backpropagating gradients. We dont want
the signal to die out, nor do we want it to explode and saturate. For
the signal to flow properly, the authors argue that we need the
variance of the outputs of each layer to be equal to the variance of
its inputs, and we also need the gradients to have equal variance
before and after flowing through a layer in the reverse direction.
!split
===== Insights from the paper by Glorot and Bengio =====
One of the insights in the 2010 paper by Glorot and Bengio was that
the vanishing/exploding gradients problems were in part due to a poor
choice of activation function. Until then most people had assumed that
if Nature had chosen to use roughly sigmoid activation functions in
biological neurons, they must be an excellent choice. But it turns out
that other activation functions behave much better in deep neural
networks, in particular the ReLU activation function, mostly because
it does not saturate for positive values (and also because it is quite
fast to compute).
!split
===== The RELU function family =====
The ReLU activation function suffers from a problem known as the dying
ReLUs: during training, some neurons effectively die, meaning they
stop outputting anything other than 0.
In some cases, you may find that half of your networks neurons are
dead, especially if you used a large learning rate. During training,
if a neurons weights get updated such that the weighted sum of the
neurons inputs is negative, it will start outputting 0. When this
happen, the neuron is unlikely to come back to life since the gradient
of the ReLU function is 0 when its input is negative.
!split
===== ELU function =====
To solve this problem, nowadays practitioners use a variant of the
ReLU function, such as the leaky ReLU discussed above or the so-called
exponential linear unit (ELU) function
!bt
\[
ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right.
\]
!et
!split
===== Which activation function should we use? =====
In general it seems that the ELU activation function is better than
the leaky ReLU function (and its variants), which is better than
ReLU. ReLU performs better than $\tanh$ which in turn performs better
than the logistic function.
If runtime performance is an issue, then you may opt for the leaky
ReLU function over the ELU function If you dont want to tweak yet
another hyperparameter, you may just use the default $\alpha$ of
$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and
computing power, you can use cross-validation or bootstrap to evaluate
other activation functions.
!split
===== More on activation functions, output layers =====
In most cases you can use the ReLU activation function in the hidden
layers (or one of its variants).
It is a bit faster to compute than other activation functions, and the
gradient descent optimization does in general not get stuck.
_For the output layer:_
* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
* For regression tasks, you can simply use no activation function at all.
!split
===== Batch Normalization =====
Batch Normalization aims to address the vanishing/exploding gradients
problems, and more generally the problem that the distribution of each
layers inputs changes during training, as the parameters of the
previous layers change.
The technique consists of adding an operation in the model just before
the activation function of each layer, simply zero-centering and
normalizing the inputs, then scaling and shifting the result using two
new parameters per layer (one for scaling, the other for shifting). In
other words, this operation lets the model learn the optimal scale and
mean of the inputs for each layer. In order to zero-center and
normalize the inputs, the algorithm needs to estimate the inputs mean
and standard deviation. It does so by evaluating the mean and standard
deviation of the inputs over the current mini-batch, from this the
name batch normalization.
!split
===== Dropout =====
It is a fairly simple algorithm: at every training step, every neuron
(including the input neurons but excluding the output neurons) has a
probability $p$ of being temporarily dropped out, meaning it will be
entirely ignored during this training step, but it may be active
during the next step.
The hyperparameter $p$ is called the dropout rate, and it is typically
set to 50%. After training, the neurons are not dropped anymore. It
is viewed as one of the most popular regularization techniques.
!split
===== Gradient Clipping =====
A popular technique to lessen the exploding gradients problem is to
simply clip the gradients during backpropagation so that they never
exceed some threshold (this is mostly useful for recurrent neural
networks).
This technique is called Gradient Clipping.
In general however, Batch
Normalization is preferred.
!split
===== A top-down perspective on Neural networks =====
The first thing we would like to do is divide the data into two or
three parts. A training set, a validation or dev (development) set,
and a test set. The test set is the data on which we want to make
predictions. The dev set is a subset of the training data we use to
check how well we are doing out-of-sample, after training the model on
the training dataset. We use the validation error as a proxy for the
test error in order to make tweaks to our model. It is crucial that we
do not use any of the test data to train the algorithm. This is a
cardinal sin in ML. Then:
o Estimate optimal error rate
o Minimize underfitting (bias) on training data set.
o Make sure you are not overfitting.
!split
===== More top-down perspectives =====
If the validation and test sets are drawn from the same distributions,
then a good performance on the validation set should lead to similarly
good performance on the test set.
However, sometimes
the training data and test data differ in subtle ways because, for
example, they are collected using slightly different methods, or
because it is cheaper to collect data in one way versus another. In
this case, there can be a mismatch between the training and test
data. This can lead to the neural network overfitting these small
differences between the test and training sets, and a poor performance
on the test set despite having a good performance on the validation
set. To rectify this, Andrew Ng suggests making two validation or dev
sets, one constructed from the training data and one constructed from
the test data. The difference between the performance of the algorithm
on these two validation sets quantifies the train-test mismatch. This
can serve as another important diagnostic when using DNNs for
supervised learning.
!split
===== Limitations of supervised learning with deep networks =====
Like all statistical methods, supervised learning using neural
networks has important limitations. This is especially important when
one seeks to apply these methods, especially to physics problems. Like
all tools, DNNs are not a universal solution. Often, the same or
better performance on a task can be achieved by using a few
hand-engineered features (or even a collection of random
features).
!split
===== Limitations of NNs =====
Here we list some of the important limitations of supervised neural network based models.
* _Need labeled data_. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
* _Supervised neural networks are extremely data intensive._ DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
!split
===== Homogeneous data =====
* _Homogeneous data._ Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e.~some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
!split
===== More limitations =====
* _Many problems are not about prediction._ In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.
Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.