This commit is contained in:
Morten Hjorth-Jensen
2021-10-01 11:27:48 +02:00
parent e8d09a1767
commit 1e7f7fd72d
7 changed files with 3741 additions and 24 deletions
+63 -5
View File
@@ -160,7 +160,7 @@ Automatically generated HTML file from DocOnce source
2,
None,
'using-gradient-descent-methods-limitations'),
('To be added', 2, None, 'to-be-added'),
('Challenge yourself', 2, None, 'challenge-yourself'),
('Friday October 1', 2, None, 'friday-october-1'),
('Stochastic Gradient Descent',
2,
@@ -178,7 +178,47 @@ Automatically generated HTML file from DocOnce source
('Program for stochastic gradient',
2,
None,
'program-for-stochastic-gradient')]}
'program-for-stochastic-gradient'),
('Momentum based GD', 2, None, 'momentum-based-gd'),
('More on momentum based approaches',
2,
None,
'more-on-momentum-based-approaches'),
('Momentum parameter', 2, None, 'momentum-parameter'),
('Second moment of the gradient',
2,
None,
'second-moment-of-the-gradient'),
('RMS prop', 2, None, 'rms-prop'),
('ADAM optimizer', 2, None, 'adam-optimizer'),
('Practical tips', 2, None, 'practical-tips'),
('Automatic differentiation',
2,
None,
'automatic-differentiation'),
('Using autograd', 2, None, 'using-autograd'),
('Autograd with more complicated functions',
2,
None,
'autograd-with-more-complicated-functions'),
('More complicated functions using the elements of their '
'arguments directly',
2,
None,
'more-complicated-functions-using-the-elements-of-their-arguments-directly'),
('Functions using mathematical functions from Numpy',
2,
None,
'functions-using-mathematical-functions-from-numpy'),
('More autograd', 2, None, 'more-autograd'),
('And with loops', 2, None, 'and-with-loops'),
('Using recursion', 2, None, 'using-recursion'),
('Unsupported functions', 2, None, 'unsupported-functions'),
('The syntax a.dot(b) when finding the dot product',
2,
None,
'the-syntax-a-dot-b-when-finding-the-dot-product'),
('Recommended to avoid', 2, None, 'recommended-to-avoid')]}
end of tocinfo -->
<body>
@@ -262,7 +302,7 @@ MathJax.Hub.Config({
<!-- navigation toc: --> <li><a href="._week39-bs044.html#gradient-descent-and-ridge" style="font-size: 80%;">Gradient descent and Ridge</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs045.html#program-example-for-gradient-descent-with-ridge-regression" style="font-size: 80%;">Program example for gradient descent with Ridge Regression</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs046.html#using-gradient-descent-methods-limitations" style="font-size: 80%;">Using gradient descent methods, limitations</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs047.html#to-be-added" style="font-size: 80%;">To be added</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs047.html#challenge-yourself" style="font-size: 80%;">Challenge yourself</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs048.html#friday-october-1" style="font-size: 80%;">Friday October 1</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs049.html#stochastic-gradient-descent" style="font-size: 80%;">Stochastic Gradient Descent</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs050.html#computation-of-gradients" style="font-size: 80%;">Computation of gradients</a></li>
@@ -272,6 +312,24 @@ MathJax.Hub.Config({
<!-- navigation toc: --> <li><a href="._week39-bs054.html#when-do-we-stop" style="font-size: 80%;">When do we stop?</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs055.html#slightly-different-approach" style="font-size: 80%;">Slightly different approach</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs056.html#program-for-stochastic-gradient" style="font-size: 80%;">Program for stochastic gradient</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs057.html#momentum-based-gd" style="font-size: 80%;">Momentum based GD</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs058.html#more-on-momentum-based-approaches" style="font-size: 80%;">More on momentum based approaches</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs059.html#momentum-parameter" style="font-size: 80%;">Momentum parameter</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs060.html#second-moment-of-the-gradient" style="font-size: 80%;">Second moment of the gradient</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs061.html#rms-prop" style="font-size: 80%;">RMS prop</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs062.html#adam-optimizer" style="font-size: 80%;">ADAM optimizer</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs063.html#practical-tips" style="font-size: 80%;">Practical tips</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs064.html#automatic-differentiation" style="font-size: 80%;">Automatic differentiation</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs065.html#using-autograd" style="font-size: 80%;">Using autograd</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs066.html#autograd-with-more-complicated-functions" style="font-size: 80%;">Autograd with more complicated functions</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs067.html#more-complicated-functions-using-the-elements-of-their-arguments-directly" style="font-size: 80%;">More complicated functions using the elements of their arguments directly</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs068.html#functions-using-mathematical-functions-from-numpy" style="font-size: 80%;">Functions using mathematical functions from Numpy</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs069.html#more-autograd" style="font-size: 80%;">More autograd</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs070.html#and-with-loops" style="font-size: 80%;">And with loops</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs071.html#using-recursion" style="font-size: 80%;">Using recursion</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs072.html#unsupported-functions" style="font-size: 80%;">Unsupported functions</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs073.html#the-syntax-a-dot-b-when-finding-the-dot-product" style="font-size: 80%;">The syntax a.dot(b) when finding the dot product</a></li>
<!-- navigation toc: --> <li><a href="._week39-bs074.html#recommended-to-avoid" style="font-size: 80%;">Recommended to avoid</a></li>
</ul>
</li>
@@ -306,7 +364,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Sep 30, 2021</h4></center> <!-- date -->
<center><h4>Oct 1, 2021</h4></center> <!-- date -->
<br>
<p>
@@ -330,7 +388,7 @@ MathJax.Hub.Config({
<li><a href="._week39-bs008.html">9</a></li>
<li><a href="._week39-bs009.html">10</a></li>
<li><a href="">...</a></li>
<li><a href="._week39-bs056.html">57</a></li>
<li><a href="._week39-bs074.html">75</a></li>
<li><a href="._week39-bs001.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+697 -3
View File
@@ -148,7 +148,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>&nbsp;<br>
<center><h4>Sep 30, 2021</h4></center> <!-- date -->
<center><h4>Oct 1, 2021</h4></center> <!-- date -->
<br>
<p>
@@ -1659,10 +1659,10 @@ plt.show()
<section>
<h2 id="to-be-added">To be added </h2>
<h2 id="challenge-yourself">Challenge yourself </h2>
<p>
We will add here an example which computes the likelihood \( p_i \), sets up the gradient and the Hessian matrix.
Write a code which implements gradient descent for a logistic regression example.
</section>
@@ -1936,6 +1936,700 @@ plt.show()
</section>
<section>
<h2 id="momentum-based-gd">Momentum based GD </h2>
<p>
The stochastic gradient descent (SGD) is almost always used with a
<em>momentum</em> or inertia term that serves as a memory of the direction we
are moving in parameter space. This is typically implemented as
follows
<p>&nbsp;<br>
$$
\begin{align}
\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\
\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t},
\tag{2}
\end{align}
$$
<p>&nbsp;<br>
<p>
where we have introduced a momentum parameter \( \gamma \), with
\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to
indicate the gradient is to be taken over a different mini-batch at
each step. We call this algorithm gradient descent with momentum
(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a
running average of recently encountered gradients and
\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory
used in the averaging procedure. Consistent with this, when
\( \gamma=0 \), this just reduces down to ordinary SGD as discussed
earlier. An equivalent way of writing the updates is
<p>&nbsp;<br>
$$
\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t),
$$
<p>&nbsp;<br>
where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).
</section>
<section>
<h2 id="more-on-momentum-based-approaches">More on momentum based approaches </h2>
<p>
Let us try to get more intuition from these equations. It is helpful
to consider a simple physical analogy with a particle of mass \( m \)
moving in a viscous medium with drag coefficient \( \mu \) and potential
\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \),
then its motion is described by
<p>&nbsp;<br>
$$
m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}).
$$
<p>&nbsp;<br>
<p>
We can discretize this equation in the usual way to get
<p>&nbsp;<br>
$$
m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}).
$$
<p>&nbsp;<br>
<p>
Rearranging this equation, we can rewrite this as
<p>&nbsp;<br>
$$
\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t.
$$
<p>&nbsp;<br>
</section>
<section>
<h2 id="momentum-parameter">Momentum parameter </h2>
<p>
Notice that this equation is identical to previous one if we identify
the position of the particle, \( \mathbf{w} \), with the parameters
\( \boldsymbol{\theta} \). This allows us to identify the momentum
parameter and learning rate with the mass of the particle and the
viscous drag as:
<p>&nbsp;<br>
$$
\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}.
$$
<p>&nbsp;<br>
<p>
Thus, as the name suggests, the momentum parameter is proportional to
the mass of the particle and effectively provides inertia.
Furthermore, in the large viscosity/small learning rate limit, our
memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \).
<p>
Why is momentum useful? SGD momentum helps the gradient descent
algorithm gain speed in directions with persistent but small gradients
even in the presence of stochasticity, while suppressing oscillations
in high-curvature directions. This becomes especially important in
situations where the landscape is shallow and flat in some directions
and narrow and steep in others. It has been argued that first-order
methods (with appropriate initial conditions) can perform comparable
to more expensive second order methods, especially in the context of
complex deep learning models.
<p>
These beneficial properties of momentum can sometimes become even more
pronounced by using a slight modification of the classical momentum
algorithm called Nesterov Accelerated Gradient (NAG).
<p>
In the NAG algorithm, rather than calculating the gradient at the
current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one
calculates the gradient at the expected value of the parameters given
our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma
\mathbf{v}_{t-1}) \). This yields the NAG update rule
<p>&nbsp;<br>
$$
\begin{align}
\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\
\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}.
\tag{3}
\end{align}
$$
<p>&nbsp;<br>
<p>
One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).
</section>
<section>
<h2 id="second-moment-of-the-gradient">Second moment of the gradient </h2>
<p>
In stochastic gradient descent, with and without momentum, we still
have to specify a schedule for tuning the learning rates \( \eta_t \)
as a function of time. As discussed in the context of Newton's
method, this presents a number of dilemmas. The learning rate is
limited by the steepest direction which can change depending on the
current position in the landscape. To circumvent this problem, ideally
our algorithm would keep track of curvature and take large steps in
shallow, flat directions and small steps in steep, narrow directions.
Second-order methods accomplish this by calculating or approximating
the Hessian and normalizing the learning rate by the
curvature. However, this is very computationally expensive for
extremely large models. Ideally, we would like to be able to
adaptively change the step size to match the landscape without paying
the steep computational price of calculating or approximating
Hessians.
<p>
Recently, a number of methods have been introduced that accomplish
this by tracking not only the gradient, but also the second moment of
the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and
ADAM.
</section>
<section>
<h2 id="rms-prop">RMS prop </h2>
<p>
In RMS prop, in addition to keeping a running average of the first
moment of the gradient, we also keep track of the second moment
denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule
for RMS prop is given by
<p>&nbsp;<br>
$$
\begin{align}
\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta})
\tag{4}\\
\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\
\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber
\end{align}
$$
<p>&nbsp;<br>
<p>
where \( \beta \) controls the averaging time of the second moment and is
typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate
typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a
small regularization constant to prevent divergences. Multiplication
and division by vectors is understood as an element-wise operation. It
is clear from this formula that the learning rate is reduced in
directions where the norm of the gradient is consistently large. This
greatly speeds up the convergence by allowing us to use a larger
learning rate for flat directions.
</section>
<section>
<h2 id="adam-optimizer">ADAM optimizer </h2>
<p>
A related algorithm is the ADAM optimizer. In ADAM, we keep a running
average of both the first and second moment of the gradient and use
this information to adaptively change the learning rate for different
parameters. In addition to keeping a running average of the first and
second moments of the gradient
(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and
\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM
performs an additional bias correction to account for the fact that we
are estimating the first two moments of the gradient using a running
average (denoted by the hats in the update rule below). The update
rule for ADAM is given by (where multiplication and division are once
again understood to be element-wise operations below)
<p>&nbsp;<br>
$$
\begin{align}
\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta})
\tag{5}\\
\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\
\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\
\boldsymbol{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\
\boldsymbol{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\
\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \boldsymbol{\mathbf{m}}_t \over \sqrt{\boldsymbol{\mathbf{s}}_t} +\epsilon}, \nonumber \\
\tag{6}
\end{align}
$$
<p>&nbsp;<br>
<p>
where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and
second moment and are typically taken to be \( 0.9 \) and \( 0.99 \)
respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop.
<p>
Like in RMSprop, the effective step size of a parameter depends on the
magnitude of its gradient squared. To understand this better, let us
rewrite this expression in terms of the variance
\( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t -
(\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The
update rule for this parameter is given by
<p>&nbsp;<br>
$$
\Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}.
$$
<p>&nbsp;<br>
</section>
<section>
<h2 id="practical-tips">Practical tips </h2>
<ul>
<p><li> <b>Randomize the data when making mini-batches</b>. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.</li>
<p><li> <b>Transform your inputs</b>. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.</li>
<p><li> <b>Monitor the out-of-sample performance.</b> Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This <em>early stopping</em> significantly improves performance in many settings.</li>
<p><li> <b>Adaptive optimization methods don't always have good generalization.</b> Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.</li>
</ul>
<p>
Geron's text, see chapter 11, has several interesting discussions.
</section>
<section>
<h2 id="automatic-differentiation">Automatic differentiation </h2>
<p>
<a href="https://en.wikipedia.org/wiki/Automatic_differentiation" target="_blank">Automatic differentiation (AD)</a>,
also called algorithmic
differentiation or computational differentiation,is a set of
techniques to numerically evaluate the derivative of a function
specified by a computer program. AD exploits the fact that every
computer program, no matter how complicated, executes a sequence of
elementary arithmetic operations (addition, subtraction,
multiplication, division, etc.) and elementary functions (exp, log,
sin, cos, etc.). By applying the chain rule repeatedly to these
operations, derivatives of arbitrary order can be computed
automatically, accurately to working precision, and using at most a
small constant factor more arithmetic operations than the original
program.
<p>
Automatic differentiation is neither:
<ul>
<p><li> Symbolic differentiation, nor</li>
<p><li> Numerical differentiation (the method of finite differences).</li>
</ul>
<p>
Symbolic differentiation can lead to inefficient code and faces the
difficulty of converting a computer program into a single expression,
while numerical differentiation can introduce round-off errors in the
discretization process and cancellation
<p>
Python has tools for so-called <b>automatic differentiation</b>.
Consider the following example
<p>&nbsp;<br>
$$
f(x) = \sin\left(2\pi x + x^2\right)
$$
<p>&nbsp;<br>
which has the following derivative
<p>&nbsp;<br>
$$
f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right)
$$
<p>&nbsp;<br>
Using <b>autograd</b> we have
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #228B22"># To do elementwise differentiation:</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> elementwise_grad <span style="color: #8B008B; font-weight: bold">as</span> egrad
<span style="color: #228B22"># To plot:</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">def</span> <span style="color: #008b45">f</span>(x):
<span style="color: #8B008B; font-weight: bold">return</span> np.sin(<span style="color: #B452CD">2</span>*np.pi*x + x**<span style="color: #B452CD">2</span>)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f_grad_analytic</span>(x):
<span style="color: #8B008B; font-weight: bold">return</span> np.cos(<span style="color: #B452CD">2</span>*np.pi*x + x**<span style="color: #B452CD">2</span>)*(<span style="color: #B452CD">2</span>*np.pi + <span style="color: #B452CD">2</span>*x)
<span style="color: #228B22"># Do the comparison:</span>
x = np.linspace(<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1000</span>)
f_grad = egrad(f)
computed = f_grad(x)
analytic = f_grad_analytic(x)
plt.title(<span style="color: #CD5555">&#39;Derivative computed from Autograd compared with the analytical derivative&#39;</span>)
plt.plot(x,computed,label=<span style="color: #CD5555">&#39;autograd&#39;</span>)
plt.plot(x,analytic,label=<span style="color: #CD5555">&#39;analytic&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;x&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;y&#39;</span>)
plt.legend()
plt.show()
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The max absolute difference is: %g&quot;</span>%(np.max(np.abs(computed - analytic))))
</pre></div>
</section>
<section>
<h2 id="using-autograd">Using autograd </h2>
<p>
Here we
experiment with what kind of functions Autograd is capable
of finding the gradient of. The following Python functions are just
meant to illustrate what Autograd can do, but please feel free to
experiment with other, possibly more complicated, functions as well.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f1</span>(x):
<span style="color: #8B008B; font-weight: bold">return</span> x**<span style="color: #B452CD">3</span> + <span style="color: #B452CD">1</span>
f1_grad = grad(f1)
<span style="color: #228B22"># Remember to send in float as argument to the computed gradient from Autograd!</span>
a = <span style="color: #B452CD">1.0</span>
<span style="color: #228B22"># See the evaluated gradient at a using autograd:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The gradient of f1 evaluated at a = %g using autograd is: %g&quot;</span>%(a,f1_grad(a)))
<span style="color: #228B22"># Compare with the analytical derivative, that is f1&#39;(x) = 3*x**2 </span>
grad_analytical = <span style="color: #B452CD">3</span>*a**<span style="color: #B452CD">2</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g&quot;</span>%(a,grad_analytical))
</pre></div>
</section>
<section>
<h2 id="autograd-with-more-complicated-functions">Autograd with more complicated functions </h2>
<p>
To differentiate with respect to two (or more) arguments of a Python
function, Autograd need to know at which variable the function if
being differentiated with respect to.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f2</span>(x1,x2):
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">3</span>*x1**<span style="color: #B452CD">3</span> + x2*(x1 - <span style="color: #B452CD">5</span>) + <span style="color: #B452CD">1</span>
<span style="color: #228B22"># By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1</span>
f2_grad_x1 = grad(f2,<span style="color: #B452CD">0</span>)
<span style="color: #228B22"># ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad</span>
f2_grad_x2 = grad(f2,<span style="color: #B452CD">1</span>)
x1 = <span style="color: #B452CD">1.0</span>
x2 = <span style="color: #B452CD">3.0</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Evaluating at x1 = %g, x2 = %g&quot;</span>%(x1,x2))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;-&quot;</span>*<span style="color: #B452CD">30</span>)
<span style="color: #228B22"># Compare with the analytical derivatives:</span>
<span style="color: #228B22"># Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:</span>
f2_grad_x1_analytical = <span style="color: #B452CD">9</span>*x1**<span style="color: #B452CD">2</span> + x2
<span style="color: #228B22"># Derivative of f2 w.r.t x2 is: x1 - 5:</span>
f2_grad_x2_analytical = x1 - <span style="color: #B452CD">5</span>
<span style="color: #228B22"># See the evaluated derivations:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The derivative of f2 w.r.t x1: %g&quot;</span>%( f2_grad_x1(x1,x2) ))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical derivative of f2 w.r.t x1: %g&quot;</span>%( f2_grad_x1(x1,x2) ))
<span style="color: #658b00">print</span>()
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The derivative of f2 w.r.t x2: %g&quot;</span>%( f2_grad_x2(x1,x2) ))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical derivative of f2 w.r.t x2: %g&quot;</span>%( f2_grad_x2(x1,x2) ))
</pre></div>
<p>
Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.
</section>
<section>
<h2 id="more-complicated-functions-using-the-elements-of-their-arguments-directly">More complicated functions using the elements of their arguments directly </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f3</span>(x): <span style="color: #228B22"># Assumes x is an array of length 5 or higher</span>
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">2</span>*x[<span style="color: #B452CD">0</span>] + <span style="color: #B452CD">3</span>*x[<span style="color: #B452CD">1</span>] + <span style="color: #B452CD">5</span>*x[<span style="color: #B452CD">2</span>] + <span style="color: #B452CD">7</span>*x[<span style="color: #B452CD">3</span>] + <span style="color: #B452CD">11</span>*x[<span style="color: #B452CD">4</span>]**<span style="color: #B452CD">2</span>
f3_grad = grad(f3)
x = np.linspace(<span style="color: #B452CD">0</span>,<span style="color: #B452CD">4</span>,<span style="color: #B452CD">5</span>)
<span style="color: #228B22"># Print the computed gradient:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed gradient of f3 is: &quot;</span>, f3_grad(x))
<span style="color: #228B22"># The analytical gradient is: (2, 3, 5, 7, 22*x[4])</span>
f3_grad_analytical = np.array([<span style="color: #B452CD">2</span>, <span style="color: #B452CD">3</span>, <span style="color: #B452CD">5</span>, <span style="color: #B452CD">7</span>, <span style="color: #B452CD">22</span>*x[<span style="color: #B452CD">4</span>]])
<span style="color: #228B22"># Print the analytical gradient:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical gradient of f3 is: &quot;</span>, f3_grad_analytical)
</pre></div>
<p>
Note that in this case, when sending an array as input argument, the
output from Autograd is another array. This is the true gradient of
the function, as opposed to the function in the previous example. By
using arrays to represent the variables, the output from Autograd
might be easier to work with, as the output is closer to what one
could expect form a gradient-evaluting function.
</section>
<section>
<h2 id="functions-using-mathematical-functions-from-numpy">Functions using mathematical functions from Numpy </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f4</span>(x):
<span style="color: #8B008B; font-weight: bold">return</span> np.sqrt(<span style="color: #B452CD">1</span>+x**<span style="color: #B452CD">2</span>) + np.exp(x) + np.sin(<span style="color: #B452CD">2</span>*np.pi*x)
f4_grad = grad(f4)
x = <span style="color: #B452CD">2.7</span>
<span style="color: #228B22"># Print the computed derivative:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f4 at x = %g is: %g&quot;</span>%(x,f4_grad(x)))
<span style="color: #228B22"># The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi</span>
f4_grad_analytical = x/np.sqrt(<span style="color: #B452CD">1</span> + x**<span style="color: #B452CD">2</span>) + np.exp(x) + np.cos(<span style="color: #B452CD">2</span>*np.pi*x)*<span style="color: #B452CD">2</span>*np.pi
<span style="color: #228B22"># Print the analytical gradient:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical gradient of f4 at x = %g is: %g&quot;</span>%(x,f4_grad_analytical))
</pre></div>
</section>
<section>
<h2 id="more-autograd">More autograd </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f5</span>(x):
<span style="color: #8B008B; font-weight: bold">if</span> x &gt;= <span style="color: #B452CD">0</span>:
<span style="color: #8B008B; font-weight: bold">return</span> x**<span style="color: #B452CD">2</span>
<span style="color: #8B008B; font-weight: bold">else</span>:
<span style="color: #8B008B; font-weight: bold">return</span> -<span style="color: #B452CD">3</span>*x + <span style="color: #B452CD">1</span>
f5_grad = grad(f5)
x = <span style="color: #B452CD">2.7</span>
<span style="color: #228B22"># Print the computed derivative:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f5 at x = %g is: %g&quot;</span>%(x,f5_grad(x)))
</pre></div>
</section>
<section>
<h2 id="and-with-loops">And with loops </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f6_for</span>(x):
val = <span style="color: #B452CD">0</span>
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">10</span>):
val = val + x**i
<span style="color: #8B008B; font-weight: bold">return</span> val
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f6_while</span>(x):
val = <span style="color: #B452CD">0</span>
i = <span style="color: #B452CD">0</span>
<span style="color: #8B008B; font-weight: bold">while</span> i &lt; <span style="color: #B452CD">10</span>:
val = val + x**i
i = i + <span style="color: #B452CD">1</span>
<span style="color: #8B008B; font-weight: bold">return</span> val
f6_for_grad = grad(f6_for)
f6_while_grad = grad(f6_while)
x = <span style="color: #B452CD">0.5</span>
<span style="color: #228B22"># Print the computed derivaties of f6_for and f6_while</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f6_for at x = %g is: %g&quot;</span>%(x,f6_for_grad(x)))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f6_while at x = %g is: %g&quot;</span>%(x,f6_while_grad(x)))
</pre></div>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #228B22"># Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9</span>
<span style="color: #228B22"># The analytical derivative is: sum(i*x**(i-1)) </span>
f6_grad_analytical = <span style="color: #B452CD">0</span>
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">10</span>):
f6_grad_analytical += i*x**(i-<span style="color: #B452CD">1</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical derivative of f6 at x = %g is: %g&quot;</span>%(x,f6_grad_analytical))
</pre></div>
</section>
<section>
<h2 id="using-recursion">Using recursion </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f7</span>(n): <span style="color: #228B22"># Assume that n is an integer</span>
<span style="color: #8B008B; font-weight: bold">if</span> n == <span style="color: #B452CD">1</span> <span style="color: #8B008B">or</span> n == <span style="color: #B452CD">0</span>:
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">1</span>
<span style="color: #8B008B; font-weight: bold">else</span>:
<span style="color: #8B008B; font-weight: bold">return</span> n*f7(n-<span style="color: #B452CD">1</span>)
f7_grad = grad(f7)
n = <span style="color: #B452CD">2.0</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f7 at n = %d is: %g&quot;</span>%(n,f7_grad(n)))
<span style="color: #228B22"># The function f7 is an implementation of the factorial of n.</span>
<span style="color: #228B22"># By using the product rule, one can find that the derivative is:</span>
f7_grad_analytical = <span style="color: #B452CD">0</span>
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #658b00">int</span>(n)-<span style="color: #B452CD">1</span>):
tmp = <span style="color: #B452CD">1</span>
<span style="color: #8B008B; font-weight: bold">for</span> k <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #658b00">int</span>(n)-<span style="color: #B452CD">1</span>):
<span style="color: #8B008B; font-weight: bold">if</span> k != i:
tmp *= (n - k)
f7_grad_analytical += tmp
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical derivative of f7 at n = %d is: %g&quot;</span>%(n,f7_grad_analytical))
</pre></div>
<p>
Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.
</section>
<section>
<h2 id="unsupported-functions">Unsupported functions </h2>
Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.
<p>
Assigning a value to the variable being differentiated with respect to
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f8</span>(x): <span style="color: #228B22"># Assume x is an array</span>
x[<span style="color: #B452CD">2</span>] = <span style="color: #B452CD">3</span>
<span style="color: #8B008B; font-weight: bold">return</span> x*<span style="color: #B452CD">2</span>
f8_grad = grad(f8)
x = <span style="color: #B452CD">8.4</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The derivative of f8 is:&quot;</span>,f8_grad(x))
</pre></div>
<p>
Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.
</section>
<section>
<h2 id="the-syntax-a-dot-b-when-finding-the-dot-product">The syntax a.dot(b) when finding the dot product </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f9</span>(a): <span style="color: #228B22"># Assume a is an array with 2 elements</span>
b = np.array([<span style="color: #B452CD">1.0</span>,<span style="color: #B452CD">2.0</span>])
<span style="color: #8B008B; font-weight: bold">return</span> a.dot(b)
f9_grad = grad(f9)
x = np.array([<span style="color: #B452CD">1.0</span>,<span style="color: #B452CD">0.0</span>])
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The derivative of f9 is:&quot;</span>,f9_grad(x))
</pre></div>
<p>
Here we are told that the 'dot' function does not belong to Autograd's
version of a Numpy array. To overcome this, an alternative syntax
which also computed the dot product can be used:
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f9_alternative</span>(x): <span style="color: #228B22"># Assume a is an array with 2 elements</span>
b = np.array([<span style="color: #B452CD">1.0</span>,<span style="color: #B452CD">2.0</span>])
<span style="color: #8B008B; font-weight: bold">return</span> np.dot(x,b) <span style="color: #228B22"># The same as x_1*b_1 + x_2*b_2</span>
f9_alternative_grad = grad(f9_alternative)
x = np.array([<span style="color: #B452CD">3.0</span>,<span style="color: #B452CD">0.0</span>])
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The gradient of f9 is:&quot;</span>,f9_alternative_grad(x))
<span style="color: #228B22"># The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively</span>
<span style="color: #228B22"># w.r.t x is (b_1, b_2).</span>
</pre></div>
</section>
<section>
<h2 id="recommended-to-avoid">Recommended to avoid </h2>
The documentation recommends to avoid inplace operations such as
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span>a += b
a -= b
a*= b
a /=b
</pre></div>
</section>
</div> <!-- class="slides" -->
</div> <!-- class="reveal" -->
+706 -5
View File
@@ -180,7 +180,7 @@ div { text-align: justify; text-justify: inter-word; }
2,
None,
'using-gradient-descent-methods-limitations'),
('To be added', 2, None, 'to-be-added'),
('Challenge yourself', 2, None, 'challenge-yourself'),
('Friday October 1', 2, None, 'friday-october-1'),
('Stochastic Gradient Descent',
2,
@@ -198,7 +198,47 @@ div { text-align: justify; text-justify: inter-word; }
('Program for stochastic gradient',
2,
None,
'program-for-stochastic-gradient')]}
'program-for-stochastic-gradient'),
('Momentum based GD', 2, None, 'momentum-based-gd'),
('More on momentum based approaches',
2,
None,
'more-on-momentum-based-approaches'),
('Momentum parameter', 2, None, 'momentum-parameter'),
('Second moment of the gradient',
2,
None,
'second-moment-of-the-gradient'),
('RMS prop', 2, None, 'rms-prop'),
('ADAM optimizer', 2, None, 'adam-optimizer'),
('Practical tips', 2, None, 'practical-tips'),
('Automatic differentiation',
2,
None,
'automatic-differentiation'),
('Using autograd', 2, None, 'using-autograd'),
('Autograd with more complicated functions',
2,
None,
'autograd-with-more-complicated-functions'),
('More complicated functions using the elements of their '
'arguments directly',
2,
None,
'more-complicated-functions-using-the-elements-of-their-arguments-directly'),
('Functions using mathematical functions from Numpy',
2,
None,
'functions-using-mathematical-functions-from-numpy'),
('More autograd', 2, None, 'more-autograd'),
('And with loops', 2, None, 'and-with-loops'),
('Using recursion', 2, None, 'using-recursion'),
('Unsupported functions', 2, None, 'unsupported-functions'),
('The syntax a.dot(b) when finding the dot product',
2,
None,
'the-syntax-a-dot-b-when-finding-the-dot-product'),
('Recommended to avoid', 2, None, 'recommended-to-avoid')]}
end of tocinfo -->
<body>
@@ -240,7 +280,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Sep 30, 2021</h4></center> <!-- date -->
<center><h4>Oct 1, 2021</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -1637,10 +1677,10 @@ plt.show()
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="to-be-added">To be added </h2>
<h2 id="challenge-yourself">Challenge yourself </h2>
<p>
We will add here an example which computes the likelihood \( p_i \), sets up the gradient and the Hessian matrix.
Write a code which implements gradient descent for a logistic regression example.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -1901,6 +1941,667 @@ plt.show()
<p>
<b>Challenge</b>: try to write a similar code for a Logistic Regression case.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="momentum-based-gd">Momentum based GD </h2>
<p>
The stochastic gradient descent (SGD) is almost always used with a
<em>momentum</em> or inertia term that serves as a memory of the direction we
are moving in parameter space. This is typically implemented as
follows
$$
\begin{align}
\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\
\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t},
\label{_auto1}
\end{align}
$$
<p>
where we have introduced a momentum parameter \( \gamma \), with
\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to
indicate the gradient is to be taken over a different mini-batch at
each step. We call this algorithm gradient descent with momentum
(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a
running average of recently encountered gradients and
\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory
used in the averaging procedure. Consistent with this, when
\( \gamma=0 \), this just reduces down to ordinary SGD as discussed
earlier. An equivalent way of writing the updates is
$$
\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t),
$$
where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-on-momentum-based-approaches">More on momentum based approaches </h2>
<p>
Let us try to get more intuition from these equations. It is helpful
to consider a simple physical analogy with a particle of mass \( m \)
moving in a viscous medium with drag coefficient \( \mu \) and potential
\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \),
then its motion is described by
$$
m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}).
$$
<p>
We can discretize this equation in the usual way to get
$$
m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}).
$$
<p>
Rearranging this equation, we can rewrite this as
$$
\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="momentum-parameter">Momentum parameter </h2>
<p>
Notice that this equation is identical to previous one if we identify
the position of the particle, \( \mathbf{w} \), with the parameters
\( \boldsymbol{\theta} \). This allows us to identify the momentum
parameter and learning rate with the mass of the particle and the
viscous drag as:
$$
\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}.
$$
<p>
Thus, as the name suggests, the momentum parameter is proportional to
the mass of the particle and effectively provides inertia.
Furthermore, in the large viscosity/small learning rate limit, our
memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \).
<p>
Why is momentum useful? SGD momentum helps the gradient descent
algorithm gain speed in directions with persistent but small gradients
even in the presence of stochasticity, while suppressing oscillations
in high-curvature directions. This becomes especially important in
situations where the landscape is shallow and flat in some directions
and narrow and steep in others. It has been argued that first-order
methods (with appropriate initial conditions) can perform comparable
to more expensive second order methods, especially in the context of
complex deep learning models.
<p>
These beneficial properties of momentum can sometimes become even more
pronounced by using a slight modification of the classical momentum
algorithm called Nesterov Accelerated Gradient (NAG).
<p>
In the NAG algorithm, rather than calculating the gradient at the
current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one
calculates the gradient at the expected value of the parameters given
our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma
\mathbf{v}_{t-1}) \). This yields the NAG update rule
$$
\begin{align}
\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\
\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}.
\label{_auto2}
\end{align}
$$
<p>
One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="second-moment-of-the-gradient">Second moment of the gradient </h2>
<p>
In stochastic gradient descent, with and without momentum, we still
have to specify a schedule for tuning the learning rates \( \eta_t \)
as a function of time. As discussed in the context of Newton's
method, this presents a number of dilemmas. The learning rate is
limited by the steepest direction which can change depending on the
current position in the landscape. To circumvent this problem, ideally
our algorithm would keep track of curvature and take large steps in
shallow, flat directions and small steps in steep, narrow directions.
Second-order methods accomplish this by calculating or approximating
the Hessian and normalizing the learning rate by the
curvature. However, this is very computationally expensive for
extremely large models. Ideally, we would like to be able to
adaptively change the step size to match the landscape without paying
the steep computational price of calculating or approximating
Hessians.
<p>
Recently, a number of methods have been introduced that accomplish
this by tracking not only the gradient, but also the second moment of
the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and
ADAM.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="rms-prop">RMS prop </h2>
<p>
In RMS prop, in addition to keeping a running average of the first
moment of the gradient, we also keep track of the second moment
denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule
for RMS prop is given by
$$
\begin{align}
\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta})
\label{_auto3}\\
\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\
\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber
\end{align}
$$
<p>
where \( \beta \) controls the averaging time of the second moment and is
typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate
typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a
small regularization constant to prevent divergences. Multiplication
and division by vectors is understood as an element-wise operation. It
is clear from this formula that the learning rate is reduced in
directions where the norm of the gradient is consistently large. This
greatly speeds up the convergence by allowing us to use a larger
learning rate for flat directions.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="adam-optimizer">ADAM optimizer </h2>
<p>
A related algorithm is the ADAM optimizer. In ADAM, we keep a running
average of both the first and second moment of the gradient and use
this information to adaptively change the learning rate for different
parameters. In addition to keeping a running average of the first and
second moments of the gradient
(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and
\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM
performs an additional bias correction to account for the fact that we
are estimating the first two moments of the gradient using a running
average (denoted by the hats in the update rule below). The update
rule for ADAM is given by (where multiplication and division are once
again understood to be element-wise operations below)
$$
\begin{align}
\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta})
\label{_auto4}\\
\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\
\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\
\boldsymbol{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\
\boldsymbol{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\
\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \boldsymbol{\mathbf{m}}_t \over \sqrt{\boldsymbol{\mathbf{s}}_t} +\epsilon}, \nonumber \\
\label{_auto5}
\end{align}
$$
<p>
where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and
second moment and are typically taken to be \( 0.9 \) and \( 0.99 \)
respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop.
<p>
Like in RMSprop, the effective step size of a parameter depends on the
magnitude of its gradient squared. To understand this better, let us
rewrite this expression in terms of the variance
\( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t -
(\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The
update rule for this parameter is given by
$$
\Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="practical-tips">Practical tips </h2>
<ul>
<li> <b>Randomize the data when making mini-batches</b>. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.</li>
<li> <b>Transform your inputs</b>. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.</li>
<li> <b>Monitor the out-of-sample performance.</b> Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This <em>early stopping</em> significantly improves performance in many settings.</li>
<li> <b>Adaptive optimization methods don't always have good generalization.</b> Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.</li>
</ul>
Geron's text, see chapter 11, has several interesting discussions.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="automatic-differentiation">Automatic differentiation </h2>
<p>
<a href="https://en.wikipedia.org/wiki/Automatic_differentiation" target="_blank">Automatic differentiation (AD)</a>,
also called algorithmic
differentiation or computational differentiation,is a set of
techniques to numerically evaluate the derivative of a function
specified by a computer program. AD exploits the fact that every
computer program, no matter how complicated, executes a sequence of
elementary arithmetic operations (addition, subtraction,
multiplication, division, etc.) and elementary functions (exp, log,
sin, cos, etc.). By applying the chain rule repeatedly to these
operations, derivatives of arbitrary order can be computed
automatically, accurately to working precision, and using at most a
small constant factor more arithmetic operations than the original
program.
<p>
Automatic differentiation is neither:
<ul>
<li> Symbolic differentiation, nor</li>
<li> Numerical differentiation (the method of finite differences).</li>
</ul>
Symbolic differentiation can lead to inefficient code and faces the
difficulty of converting a computer program into a single expression,
while numerical differentiation can introduce round-off errors in the
discretization process and cancellation
<p>
Python has tools for so-called <b>automatic differentiation</b>.
Consider the following example
$$
f(x) = \sin\left(2\pi x + x^2\right)
$$
which has the following derivative
$$
f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right)
$$
Using <b>autograd</b> we have
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #228B22"># To do elementwise differentiation:</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> elementwise_grad <span style="color: #8B008B; font-weight: bold">as</span> egrad
<span style="color: #228B22"># To plot:</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">def</span> <span style="color: #008b45">f</span>(x):
<span style="color: #8B008B; font-weight: bold">return</span> np.sin(<span style="color: #B452CD">2</span>*np.pi*x + x**<span style="color: #B452CD">2</span>)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f_grad_analytic</span>(x):
<span style="color: #8B008B; font-weight: bold">return</span> np.cos(<span style="color: #B452CD">2</span>*np.pi*x + x**<span style="color: #B452CD">2</span>)*(<span style="color: #B452CD">2</span>*np.pi + <span style="color: #B452CD">2</span>*x)
<span style="color: #228B22"># Do the comparison:</span>
x = np.linspace(<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1000</span>)
f_grad = egrad(f)
computed = f_grad(x)
analytic = f_grad_analytic(x)
plt.title(<span style="color: #CD5555">&#39;Derivative computed from Autograd compared with the analytical derivative&#39;</span>)
plt.plot(x,computed,label=<span style="color: #CD5555">&#39;autograd&#39;</span>)
plt.plot(x,analytic,label=<span style="color: #CD5555">&#39;analytic&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;x&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;y&#39;</span>)
plt.legend()
plt.show()
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The max absolute difference is: %g&quot;</span>%(np.max(np.abs(computed - analytic))))
</pre></div>
<p>
<!-- !split -->
<h2 id="using-autograd">Using autograd </h2>
<p>
Here we
experiment with what kind of functions Autograd is capable
of finding the gradient of. The following Python functions are just
meant to illustrate what Autograd can do, but please feel free to
experiment with other, possibly more complicated, functions as well.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f1</span>(x):
<span style="color: #8B008B; font-weight: bold">return</span> x**<span style="color: #B452CD">3</span> + <span style="color: #B452CD">1</span>
f1_grad = grad(f1)
<span style="color: #228B22"># Remember to send in float as argument to the computed gradient from Autograd!</span>
a = <span style="color: #B452CD">1.0</span>
<span style="color: #228B22"># See the evaluated gradient at a using autograd:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The gradient of f1 evaluated at a = %g using autograd is: %g&quot;</span>%(a,f1_grad(a)))
<span style="color: #228B22"># Compare with the analytical derivative, that is f1&#39;(x) = 3*x**2 </span>
grad_analytical = <span style="color: #B452CD">3</span>*a**<span style="color: #B452CD">2</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g&quot;</span>%(a,grad_analytical))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="autograd-with-more-complicated-functions">Autograd with more complicated functions </h2>
<p>
To differentiate with respect to two (or more) arguments of a Python
function, Autograd need to know at which variable the function if
being differentiated with respect to.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f2</span>(x1,x2):
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">3</span>*x1**<span style="color: #B452CD">3</span> + x2*(x1 - <span style="color: #B452CD">5</span>) + <span style="color: #B452CD">1</span>
<span style="color: #228B22"># By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1</span>
f2_grad_x1 = grad(f2,<span style="color: #B452CD">0</span>)
<span style="color: #228B22"># ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad</span>
f2_grad_x2 = grad(f2,<span style="color: #B452CD">1</span>)
x1 = <span style="color: #B452CD">1.0</span>
x2 = <span style="color: #B452CD">3.0</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Evaluating at x1 = %g, x2 = %g&quot;</span>%(x1,x2))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;-&quot;</span>*<span style="color: #B452CD">30</span>)
<span style="color: #228B22"># Compare with the analytical derivatives:</span>
<span style="color: #228B22"># Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:</span>
f2_grad_x1_analytical = <span style="color: #B452CD">9</span>*x1**<span style="color: #B452CD">2</span> + x2
<span style="color: #228B22"># Derivative of f2 w.r.t x2 is: x1 - 5:</span>
f2_grad_x2_analytical = x1 - <span style="color: #B452CD">5</span>
<span style="color: #228B22"># See the evaluated derivations:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The derivative of f2 w.r.t x1: %g&quot;</span>%( f2_grad_x1(x1,x2) ))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical derivative of f2 w.r.t x1: %g&quot;</span>%( f2_grad_x1(x1,x2) ))
<span style="color: #658b00">print</span>()
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The derivative of f2 w.r.t x2: %g&quot;</span>%( f2_grad_x2(x1,x2) ))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical derivative of f2 w.r.t x2: %g&quot;</span>%( f2_grad_x2(x1,x2) ))
</pre></div>
<p>
Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-complicated-functions-using-the-elements-of-their-arguments-directly">More complicated functions using the elements of their arguments directly </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f3</span>(x): <span style="color: #228B22"># Assumes x is an array of length 5 or higher</span>
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">2</span>*x[<span style="color: #B452CD">0</span>] + <span style="color: #B452CD">3</span>*x[<span style="color: #B452CD">1</span>] + <span style="color: #B452CD">5</span>*x[<span style="color: #B452CD">2</span>] + <span style="color: #B452CD">7</span>*x[<span style="color: #B452CD">3</span>] + <span style="color: #B452CD">11</span>*x[<span style="color: #B452CD">4</span>]**<span style="color: #B452CD">2</span>
f3_grad = grad(f3)
x = np.linspace(<span style="color: #B452CD">0</span>,<span style="color: #B452CD">4</span>,<span style="color: #B452CD">5</span>)
<span style="color: #228B22"># Print the computed gradient:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed gradient of f3 is: &quot;</span>, f3_grad(x))
<span style="color: #228B22"># The analytical gradient is: (2, 3, 5, 7, 22*x[4])</span>
f3_grad_analytical = np.array([<span style="color: #B452CD">2</span>, <span style="color: #B452CD">3</span>, <span style="color: #B452CD">5</span>, <span style="color: #B452CD">7</span>, <span style="color: #B452CD">22</span>*x[<span style="color: #B452CD">4</span>]])
<span style="color: #228B22"># Print the analytical gradient:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical gradient of f3 is: &quot;</span>, f3_grad_analytical)
</pre></div>
<p>
Note that in this case, when sending an array as input argument, the
output from Autograd is another array. This is the true gradient of
the function, as opposed to the function in the previous example. By
using arrays to represent the variables, the output from Autograd
might be easier to work with, as the output is closer to what one
could expect form a gradient-evaluting function.
<p>
<!-- !split -->
<h2 id="functions-using-mathematical-functions-from-numpy">Functions using mathematical functions from Numpy </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f4</span>(x):
<span style="color: #8B008B; font-weight: bold">return</span> np.sqrt(<span style="color: #B452CD">1</span>+x**<span style="color: #B452CD">2</span>) + np.exp(x) + np.sin(<span style="color: #B452CD">2</span>*np.pi*x)
f4_grad = grad(f4)
x = <span style="color: #B452CD">2.7</span>
<span style="color: #228B22"># Print the computed derivative:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f4 at x = %g is: %g&quot;</span>%(x,f4_grad(x)))
<span style="color: #228B22"># The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi</span>
f4_grad_analytical = x/np.sqrt(<span style="color: #B452CD">1</span> + x**<span style="color: #B452CD">2</span>) + np.exp(x) + np.cos(<span style="color: #B452CD">2</span>*np.pi*x)*<span style="color: #B452CD">2</span>*np.pi
<span style="color: #228B22"># Print the analytical gradient:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical gradient of f4 at x = %g is: %g&quot;</span>%(x,f4_grad_analytical))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-autograd">More autograd </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f5</span>(x):
<span style="color: #8B008B; font-weight: bold">if</span> x &gt;= <span style="color: #B452CD">0</span>:
<span style="color: #8B008B; font-weight: bold">return</span> x**<span style="color: #B452CD">2</span>
<span style="color: #8B008B; font-weight: bold">else</span>:
<span style="color: #8B008B; font-weight: bold">return</span> -<span style="color: #B452CD">3</span>*x + <span style="color: #B452CD">1</span>
f5_grad = grad(f5)
x = <span style="color: #B452CD">2.7</span>
<span style="color: #228B22"># Print the computed derivative:</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f5 at x = %g is: %g&quot;</span>%(x,f5_grad(x)))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="and-with-loops">And with loops </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f6_for</span>(x):
val = <span style="color: #B452CD">0</span>
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">10</span>):
val = val + x**i
<span style="color: #8B008B; font-weight: bold">return</span> val
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f6_while</span>(x):
val = <span style="color: #B452CD">0</span>
i = <span style="color: #B452CD">0</span>
<span style="color: #8B008B; font-weight: bold">while</span> i &lt; <span style="color: #B452CD">10</span>:
val = val + x**i
i = i + <span style="color: #B452CD">1</span>
<span style="color: #8B008B; font-weight: bold">return</span> val
f6_for_grad = grad(f6_for)
f6_while_grad = grad(f6_while)
x = <span style="color: #B452CD">0.5</span>
<span style="color: #228B22"># Print the computed derivaties of f6_for and f6_while</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f6_for at x = %g is: %g&quot;</span>%(x,f6_for_grad(x)))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f6_while at x = %g is: %g&quot;</span>%(x,f6_while_grad(x)))
</pre></div>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #228B22"># Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9</span>
<span style="color: #228B22"># The analytical derivative is: sum(i*x**(i-1)) </span>
f6_grad_analytical = <span style="color: #B452CD">0</span>
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">10</span>):
f6_grad_analytical += i*x**(i-<span style="color: #B452CD">1</span>)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical derivative of f6 at x = %g is: %g&quot;</span>%(x,f6_grad_analytical))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="using-recursion">Using recursion </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f7</span>(n): <span style="color: #228B22"># Assume that n is an integer</span>
<span style="color: #8B008B; font-weight: bold">if</span> n == <span style="color: #B452CD">1</span> <span style="color: #8B008B">or</span> n == <span style="color: #B452CD">0</span>:
<span style="color: #8B008B; font-weight: bold">return</span> <span style="color: #B452CD">1</span>
<span style="color: #8B008B; font-weight: bold">else</span>:
<span style="color: #8B008B; font-weight: bold">return</span> n*f7(n-<span style="color: #B452CD">1</span>)
f7_grad = grad(f7)
n = <span style="color: #B452CD">2.0</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The computed derivative of f7 at n = %d is: %g&quot;</span>%(n,f7_grad(n)))
<span style="color: #228B22"># The function f7 is an implementation of the factorial of n.</span>
<span style="color: #228B22"># By using the product rule, one can find that the derivative is:</span>
f7_grad_analytical = <span style="color: #B452CD">0</span>
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #658b00">int</span>(n)-<span style="color: #B452CD">1</span>):
tmp = <span style="color: #B452CD">1</span>
<span style="color: #8B008B; font-weight: bold">for</span> k <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #658b00">int</span>(n)-<span style="color: #B452CD">1</span>):
<span style="color: #8B008B; font-weight: bold">if</span> k != i:
tmp *= (n - k)
f7_grad_analytical += tmp
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The analytical derivative of f7 at n = %d is: %g&quot;</span>%(n,f7_grad_analytical))
</pre></div>
<p>
Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="unsupported-functions">Unsupported functions </h2>
Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.
<p>
Assigning a value to the variable being differentiated with respect to
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f8</span>(x): <span style="color: #228B22"># Assume x is an array</span>
x[<span style="color: #B452CD">2</span>] = <span style="color: #B452CD">3</span>
<span style="color: #8B008B; font-weight: bold">return</span> x*<span style="color: #B452CD">2</span>
f8_grad = grad(f8)
x = <span style="color: #B452CD">8.4</span>
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The derivative of f8 is:&quot;</span>,f8_grad(x))
</pre></div>
<p>
Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-syntax-a-dot-b-when-finding-the-dot-product">The syntax a.dot(b) when finding the dot product </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f9</span>(a): <span style="color: #228B22"># Assume a is an array with 2 elements</span>
b = np.array([<span style="color: #B452CD">1.0</span>,<span style="color: #B452CD">2.0</span>])
<span style="color: #8B008B; font-weight: bold">return</span> a.dot(b)
f9_grad = grad(f9)
x = np.array([<span style="color: #B452CD">1.0</span>,<span style="color: #B452CD">0.0</span>])
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The derivative of f9 is:&quot;</span>,f9_grad(x))
</pre></div>
<p>
Here we are told that the 'dot' function does not belong to Autograd's
version of a Numpy array. To overcome this, an alternative syntax
which also computed the dot product can be used:
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">autograd.numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">autograd</span> <span style="color: #8B008B; font-weight: bold">import</span> grad
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">f9_alternative</span>(x): <span style="color: #228B22"># Assume a is an array with 2 elements</span>
b = np.array([<span style="color: #B452CD">1.0</span>,<span style="color: #B452CD">2.0</span>])
<span style="color: #8B008B; font-weight: bold">return</span> np.dot(x,b) <span style="color: #228B22"># The same as x_1*b_1 + x_2*b_2</span>
f9_alternative_grad = grad(f9_alternative)
x = np.array([<span style="color: #B452CD">3.0</span>,<span style="color: #B452CD">0.0</span>])
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;The gradient of f9 is:&quot;</span>,f9_alternative_grad(x))
<span style="color: #228B22"># The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively</span>
<span style="color: #228B22"># w.r.t x is (b_1, b_2).</span>
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="recommended-to-avoid">Recommended to avoid </h2>
The documentation recommends to avoid inplace operations such as
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span>a += b
a -= b
a*= b
a /=b
</pre></div>
<p>
<!-- ------------------- end of main content --------------- -->
+706 -5
View File
@@ -185,7 +185,7 @@ div { text-align: justify; text-justify: inter-word; }
2,
None,
'using-gradient-descent-methods-limitations'),
('To be added', 2, None, 'to-be-added'),
('Challenge yourself', 2, None, 'challenge-yourself'),
('Friday October 1', 2, None, 'friday-october-1'),
('Stochastic Gradient Descent',
2,
@@ -203,7 +203,47 @@ div { text-align: justify; text-justify: inter-word; }
('Program for stochastic gradient',
2,
None,
'program-for-stochastic-gradient')]}
'program-for-stochastic-gradient'),
('Momentum based GD', 2, None, 'momentum-based-gd'),
('More on momentum based approaches',
2,
None,
'more-on-momentum-based-approaches'),
('Momentum parameter', 2, None, 'momentum-parameter'),
('Second moment of the gradient',
2,
None,
'second-moment-of-the-gradient'),
('RMS prop', 2, None, 'rms-prop'),
('ADAM optimizer', 2, None, 'adam-optimizer'),
('Practical tips', 2, None, 'practical-tips'),
('Automatic differentiation',
2,
None,
'automatic-differentiation'),
('Using autograd', 2, None, 'using-autograd'),
('Autograd with more complicated functions',
2,
None,
'autograd-with-more-complicated-functions'),
('More complicated functions using the elements of their '
'arguments directly',
2,
None,
'more-complicated-functions-using-the-elements-of-their-arguments-directly'),
('Functions using mathematical functions from Numpy',
2,
None,
'functions-using-mathematical-functions-from-numpy'),
('More autograd', 2, None, 'more-autograd'),
('And with loops', 2, None, 'and-with-loops'),
('Using recursion', 2, None, 'using-recursion'),
('Unsupported functions', 2, None, 'unsupported-functions'),
('The syntax a.dot(b) when finding the dot product',
2,
None,
'the-syntax-a-dot-b-when-finding-the-dot-product'),
('Recommended to avoid', 2, None, 'recommended-to-avoid')]}
end of tocinfo -->
<body>
@@ -245,7 +285,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Sep 30, 2021</h4></center> <!-- date -->
<center><h4>Oct 1, 2021</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -1642,10 +1682,10 @@ plt<span style="color: #666666">.</span>show()
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="to-be-added">To be added </h2>
<h2 id="challenge-yourself">Challenge yourself </h2>
<p>
We will add here an example which computes the likelihood \( p_i \), sets up the gradient and the Hessian matrix.
Write a code which implements gradient descent for a logistic regression example.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -1906,6 +1946,667 @@ plt<span style="color: #666666">.</span>show()
<p>
<b>Challenge</b>: try to write a similar code for a Logistic Regression case.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="momentum-based-gd">Momentum based GD </h2>
<p>
The stochastic gradient descent (SGD) is almost always used with a
<em>momentum</em> or inertia term that serves as a memory of the direction we
are moving in parameter space. This is typically implemented as
follows
$$
\begin{align}
\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\
\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t},
\label{_auto1}
\end{align}
$$
<p>
where we have introduced a momentum parameter \( \gamma \), with
\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to
indicate the gradient is to be taken over a different mini-batch at
each step. We call this algorithm gradient descent with momentum
(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a
running average of recently encountered gradients and
\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory
used in the averaging procedure. Consistent with this, when
\( \gamma=0 \), this just reduces down to ordinary SGD as discussed
earlier. An equivalent way of writing the updates is
$$
\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t),
$$
where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-on-momentum-based-approaches">More on momentum based approaches </h2>
<p>
Let us try to get more intuition from these equations. It is helpful
to consider a simple physical analogy with a particle of mass \( m \)
moving in a viscous medium with drag coefficient \( \mu \) and potential
\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \),
then its motion is described by
$$
m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}).
$$
<p>
We can discretize this equation in the usual way to get
$$
m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}).
$$
<p>
Rearranging this equation, we can rewrite this as
$$
\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="momentum-parameter">Momentum parameter </h2>
<p>
Notice that this equation is identical to previous one if we identify
the position of the particle, \( \mathbf{w} \), with the parameters
\( \boldsymbol{\theta} \). This allows us to identify the momentum
parameter and learning rate with the mass of the particle and the
viscous drag as:
$$
\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}.
$$
<p>
Thus, as the name suggests, the momentum parameter is proportional to
the mass of the particle and effectively provides inertia.
Furthermore, in the large viscosity/small learning rate limit, our
memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \).
<p>
Why is momentum useful? SGD momentum helps the gradient descent
algorithm gain speed in directions with persistent but small gradients
even in the presence of stochasticity, while suppressing oscillations
in high-curvature directions. This becomes especially important in
situations where the landscape is shallow and flat in some directions
and narrow and steep in others. It has been argued that first-order
methods (with appropriate initial conditions) can perform comparable
to more expensive second order methods, especially in the context of
complex deep learning models.
<p>
These beneficial properties of momentum can sometimes become even more
pronounced by using a slight modification of the classical momentum
algorithm called Nesterov Accelerated Gradient (NAG).
<p>
In the NAG algorithm, rather than calculating the gradient at the
current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one
calculates the gradient at the expected value of the parameters given
our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma
\mathbf{v}_{t-1}) \). This yields the NAG update rule
$$
\begin{align}
\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\
\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}.
\label{_auto2}
\end{align}
$$
<p>
One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="second-moment-of-the-gradient">Second moment of the gradient </h2>
<p>
In stochastic gradient descent, with and without momentum, we still
have to specify a schedule for tuning the learning rates \( \eta_t \)
as a function of time. As discussed in the context of Newton's
method, this presents a number of dilemmas. The learning rate is
limited by the steepest direction which can change depending on the
current position in the landscape. To circumvent this problem, ideally
our algorithm would keep track of curvature and take large steps in
shallow, flat directions and small steps in steep, narrow directions.
Second-order methods accomplish this by calculating or approximating
the Hessian and normalizing the learning rate by the
curvature. However, this is very computationally expensive for
extremely large models. Ideally, we would like to be able to
adaptively change the step size to match the landscape without paying
the steep computational price of calculating or approximating
Hessians.
<p>
Recently, a number of methods have been introduced that accomplish
this by tracking not only the gradient, but also the second moment of
the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and
ADAM.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="rms-prop">RMS prop </h2>
<p>
In RMS prop, in addition to keeping a running average of the first
moment of the gradient, we also keep track of the second moment
denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule
for RMS prop is given by
$$
\begin{align}
\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta})
\label{_auto3}\\
\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\
\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber
\end{align}
$$
<p>
where \( \beta \) controls the averaging time of the second moment and is
typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate
typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a
small regularization constant to prevent divergences. Multiplication
and division by vectors is understood as an element-wise operation. It
is clear from this formula that the learning rate is reduced in
directions where the norm of the gradient is consistently large. This
greatly speeds up the convergence by allowing us to use a larger
learning rate for flat directions.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="adam-optimizer">ADAM optimizer </h2>
<p>
A related algorithm is the ADAM optimizer. In ADAM, we keep a running
average of both the first and second moment of the gradient and use
this information to adaptively change the learning rate for different
parameters. In addition to keeping a running average of the first and
second moments of the gradient
(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and
\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM
performs an additional bias correction to account for the fact that we
are estimating the first two moments of the gradient using a running
average (denoted by the hats in the update rule below). The update
rule for ADAM is given by (where multiplication and division are once
again understood to be element-wise operations below)
$$
\begin{align}
\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta})
\label{_auto4}\\
\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\
\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\
\boldsymbol{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\
\boldsymbol{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\
\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \boldsymbol{\mathbf{m}}_t \over \sqrt{\boldsymbol{\mathbf{s}}_t} +\epsilon}, \nonumber \\
\label{_auto5}
\end{align}
$$
<p>
where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and
second moment and are typically taken to be \( 0.9 \) and \( 0.99 \)
respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop.
<p>
Like in RMSprop, the effective step size of a parameter depends on the
magnitude of its gradient squared. To understand this better, let us
rewrite this expression in terms of the variance
\( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t -
(\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The
update rule for this parameter is given by
$$
\Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="practical-tips">Practical tips </h2>
<ul>
<li> <b>Randomize the data when making mini-batches</b>. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.</li>
<li> <b>Transform your inputs</b>. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.</li>
<li> <b>Monitor the out-of-sample performance.</b> Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This <em>early stopping</em> significantly improves performance in many settings.</li>
<li> <b>Adaptive optimization methods don't always have good generalization.</b> Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.</li>
</ul>
Geron's text, see chapter 11, has several interesting discussions.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="automatic-differentiation">Automatic differentiation </h2>
<p>
<a href="https://en.wikipedia.org/wiki/Automatic_differentiation" target="_blank">Automatic differentiation (AD)</a>,
also called algorithmic
differentiation or computational differentiation,is a set of
techniques to numerically evaluate the derivative of a function
specified by a computer program. AD exploits the fact that every
computer program, no matter how complicated, executes a sequence of
elementary arithmetic operations (addition, subtraction,
multiplication, division, etc.) and elementary functions (exp, log,
sin, cos, etc.). By applying the chain rule repeatedly to these
operations, derivatives of arbitrary order can be computed
automatically, accurately to working precision, and using at most a
small constant factor more arithmetic operations than the original
program.
<p>
Automatic differentiation is neither:
<ul>
<li> Symbolic differentiation, nor</li>
<li> Numerical differentiation (the method of finite differences).</li>
</ul>
Symbolic differentiation can lead to inefficient code and faces the
difficulty of converting a computer program into a single expression,
while numerical differentiation can introduce round-off errors in the
discretization process and cancellation
<p>
Python has tools for so-called <b>automatic differentiation</b>.
Consider the following example
$$
f(x) = \sin\left(2\pi x + x^2\right)
$$
which has the following derivative
$$
f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right)
$$
Using <b>autograd</b> we have
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.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"># To do elementwise differentiation:</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> elementwise_grad <span style="color: #008000; font-weight: bold">as</span> egrad
<span style="color: #408080; font-style: italic"># To plot:</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(x):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(<span style="color: #666666">2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x <span style="color: #666666">+</span> x<span style="color: #666666">**2</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f_grad_analytic</span>(x):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>cos(<span style="color: #666666">2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x <span style="color: #666666">+</span> x<span style="color: #666666">**2</span>)<span style="color: #666666">*</span>(<span style="color: #666666">2*</span>np<span style="color: #666666">.</span>pi <span style="color: #666666">+</span> <span style="color: #666666">2*</span>x)
<span style="color: #408080; font-style: italic"># Do the comparison:</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1000</span>)
f_grad <span style="color: #666666">=</span> egrad(f)
computed <span style="color: #666666">=</span> f_grad(x)
analytic <span style="color: #666666">=</span> f_grad_analytic(x)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Derivative computed from Autograd compared with the analytical derivative&#39;</span>)
plt<span style="color: #666666">.</span>plot(x,computed,label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;autograd&#39;</span>)
plt<span style="color: #666666">.</span>plot(x,analytic,label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;analytic&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;y&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The max absolute difference is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(computed <span style="color: #666666">-</span> analytic))))
</pre></div>
<p>
<!-- !split -->
<h2 id="using-autograd">Using autograd </h2>
<p>
Here we
experiment with what kind of functions Autograd is capable
of finding the gradient of. The following Python functions are just
meant to illustrate what Autograd can do, but please feel free to
experiment with other, possibly more complicated, functions as well.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f1</span>(x):
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">**3</span> <span style="color: #666666">+</span> <span style="color: #666666">1</span>
f1_grad <span style="color: #666666">=</span> grad(f1)
<span style="color: #408080; font-style: italic"># Remember to send in float as argument to the computed gradient from Autograd!</span>
a <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
<span style="color: #408080; font-style: italic"># See the evaluated gradient at a using autograd:</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The gradient of f1 evaluated at a = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> using autograd is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(a,f1_grad(a)))
<span style="color: #408080; font-style: italic"># Compare with the analytical derivative, that is f1&#39;(x) = 3*x**2 </span>
grad_analytical <span style="color: #666666">=</span> <span style="color: #666666">3*</span>a<span style="color: #666666">**2</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The gradient of f1 evaluated at a = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> by finding the analytic expression is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(a,grad_analytical))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="autograd-with-more-complicated-functions">Autograd with more complicated functions </h2>
<p>
To differentiate with respect to two (or more) arguments of a Python
function, Autograd need to know at which variable the function if
being differentiated with respect to.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f2</span>(x1,x2):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">3*</span>x1<span style="color: #666666">**3</span> <span style="color: #666666">+</span> x2<span style="color: #666666">*</span>(x1 <span style="color: #666666">-</span> <span style="color: #666666">5</span>) <span style="color: #666666">+</span> <span style="color: #666666">1</span>
<span style="color: #408080; font-style: italic"># By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1</span>
f2_grad_x1 <span style="color: #666666">=</span> grad(f2,<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad</span>
f2_grad_x2 <span style="color: #666666">=</span> grad(f2,<span style="color: #666666">1</span>)
x1 <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
x2 <span style="color: #666666">=</span> <span style="color: #666666">3.0</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Evaluating at x1 = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">, x2 = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(x1,x2))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;-&quot;</span><span style="color: #666666">*30</span>)
<span style="color: #408080; font-style: italic"># Compare with the analytical derivatives:</span>
<span style="color: #408080; font-style: italic"># Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:</span>
f2_grad_x1_analytical <span style="color: #666666">=</span> <span style="color: #666666">9*</span>x1<span style="color: #666666">**2</span> <span style="color: #666666">+</span> x2
<span style="color: #408080; font-style: italic"># Derivative of f2 w.r.t x2 is: x1 - 5:</span>
f2_grad_x2_analytical <span style="color: #666666">=</span> x1 <span style="color: #666666">-</span> <span style="color: #666666">5</span>
<span style="color: #408080; font-style: italic"># See the evaluated derivations:</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The derivative of f2 w.r.t x1: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>( f2_grad_x1(x1,x2) ))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The analytical derivative of f2 w.r.t x1: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>( f2_grad_x1(x1,x2) ))
<span style="color: #008000">print</span>()
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The derivative of f2 w.r.t x2: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>( f2_grad_x2(x1,x2) ))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The analytical derivative of f2 w.r.t x2: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>( f2_grad_x2(x1,x2) ))
</pre></div>
<p>
Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-complicated-functions-using-the-elements-of-their-arguments-directly">More complicated functions using the elements of their arguments directly </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f3</span>(x): <span style="color: #408080; font-style: italic"># Assumes x is an array of length 5 or higher</span>
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">2*</span>x[<span style="color: #666666">0</span>] <span style="color: #666666">+</span> <span style="color: #666666">3*</span>x[<span style="color: #666666">1</span>] <span style="color: #666666">+</span> <span style="color: #666666">5*</span>x[<span style="color: #666666">2</span>] <span style="color: #666666">+</span> <span style="color: #666666">7*</span>x[<span style="color: #666666">3</span>] <span style="color: #666666">+</span> <span style="color: #666666">11*</span>x[<span style="color: #666666">4</span>]<span style="color: #666666">**2</span>
f3_grad <span style="color: #666666">=</span> grad(f3)
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">4</span>,<span style="color: #666666">5</span>)
<span style="color: #408080; font-style: italic"># Print the computed gradient:</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The computed gradient of f3 is: &quot;</span>, f3_grad(x))
<span style="color: #408080; font-style: italic"># The analytical gradient is: (2, 3, 5, 7, 22*x[4])</span>
f3_grad_analytical <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">2</span>, <span style="color: #666666">3</span>, <span style="color: #666666">5</span>, <span style="color: #666666">7</span>, <span style="color: #666666">22*</span>x[<span style="color: #666666">4</span>]])
<span style="color: #408080; font-style: italic"># Print the analytical gradient:</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The analytical gradient of f3 is: &quot;</span>, f3_grad_analytical)
</pre></div>
<p>
Note that in this case, when sending an array as input argument, the
output from Autograd is another array. This is the true gradient of
the function, as opposed to the function in the previous example. By
using arrays to represent the variables, the output from Autograd
might be easier to work with, as the output is closer to what one
could expect form a gradient-evaluting function.
<p>
<!-- !split -->
<h2 id="functions-using-mathematical-functions-from-numpy">Functions using mathematical functions from Numpy </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f4</span>(x):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sqrt(<span style="color: #666666">1+</span>x<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(x) <span style="color: #666666">+</span> np<span style="color: #666666">.</span>sin(<span style="color: #666666">2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
f4_grad <span style="color: #666666">=</span> grad(f4)
x <span style="color: #666666">=</span> <span style="color: #666666">2.7</span>
<span style="color: #408080; font-style: italic"># Print the computed derivative:</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The computed derivative of f4 at x = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(x,f4_grad(x)))
<span style="color: #408080; font-style: italic"># The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi</span>
f4_grad_analytical <span style="color: #666666">=</span> x<span style="color: #666666">/</span>np<span style="color: #666666">.</span>sqrt(<span style="color: #666666">1</span> <span style="color: #666666">+</span> x<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(x) <span style="color: #666666">+</span> np<span style="color: #666666">.</span>cos(<span style="color: #666666">2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)<span style="color: #666666">*2*</span>np<span style="color: #666666">.</span>pi
<span style="color: #408080; font-style: italic"># Print the analytical gradient:</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The analytical gradient of f4 at x = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(x,f4_grad_analytical))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-autograd">More autograd </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f5</span>(x):
<span style="color: #008000; font-weight: bold">if</span> x <span style="color: #666666">&gt;=</span> <span style="color: #666666">0</span>:
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">**2</span>
<span style="color: #008000; font-weight: bold">else</span>:
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-3*</span>x <span style="color: #666666">+</span> <span style="color: #666666">1</span>
f5_grad <span style="color: #666666">=</span> grad(f5)
x <span style="color: #666666">=</span> <span style="color: #666666">2.7</span>
<span style="color: #408080; font-style: italic"># Print the computed derivative:</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The computed derivative of f5 at x = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(x,f5_grad(x)))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="and-with-loops">And with loops </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f6_for</span>(x):
val <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">10</span>):
val <span style="color: #666666">=</span> val <span style="color: #666666">+</span> x<span style="color: #666666">**</span>i
<span style="color: #008000; font-weight: bold">return</span> val
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f6_while</span>(x):
val <span style="color: #666666">=</span> <span style="color: #666666">0</span>
i <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">while</span> i <span style="color: #666666">&lt;</span> <span style="color: #666666">10</span>:
val <span style="color: #666666">=</span> val <span style="color: #666666">+</span> x<span style="color: #666666">**</span>i
i <span style="color: #666666">=</span> i <span style="color: #666666">+</span> <span style="color: #666666">1</span>
<span style="color: #008000; font-weight: bold">return</span> val
f6_for_grad <span style="color: #666666">=</span> grad(f6_for)
f6_while_grad <span style="color: #666666">=</span> grad(f6_while)
x <span style="color: #666666">=</span> <span style="color: #666666">0.5</span>
<span style="color: #408080; font-style: italic"># Print the computed derivaties of f6_for and f6_while</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The computed derivative of f6_for at x = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(x,f6_for_grad(x)))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The computed derivative of f6_while at x = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(x,f6_while_grad(x)))
</pre></div>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #408080; font-style: italic"># Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9</span>
<span style="color: #408080; font-style: italic"># The analytical derivative is: sum(i*x**(i-1)) </span>
f6_grad_analytical <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">10</span>):
f6_grad_analytical <span style="color: #666666">+=</span> i<span style="color: #666666">*</span>x<span style="color: #666666">**</span>(i<span style="color: #666666">-1</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The analytical derivative of f6 at x = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(x,f6_grad_analytical))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="using-recursion">Using recursion </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f7</span>(n): <span style="color: #408080; font-style: italic"># Assume that n is an integer</span>
<span style="color: #008000; font-weight: bold">if</span> n <span style="color: #666666">==</span> <span style="color: #666666">1</span> <span style="color: #AA22FF; font-weight: bold">or</span> n <span style="color: #666666">==</span> <span style="color: #666666">0</span>:
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span>
<span style="color: #008000; font-weight: bold">else</span>:
<span style="color: #008000; font-weight: bold">return</span> n<span style="color: #666666">*</span>f7(n<span style="color: #666666">-1</span>)
f7_grad <span style="color: #666666">=</span> grad(f7)
n <span style="color: #666666">=</span> <span style="color: #666666">2.0</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The computed derivative of f7 at n = </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(n,f7_grad(n)))
<span style="color: #408080; font-style: italic"># The function f7 is an implementation of the factorial of n.</span>
<span style="color: #408080; font-style: italic"># By using the product rule, one can find that the derivative is:</span>
f7_grad_analytical <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">int</span>(n)<span style="color: #666666">-1</span>):
tmp <span style="color: #666666">=</span> <span style="color: #666666">1</span>
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">int</span>(n)<span style="color: #666666">-1</span>):
<span style="color: #008000; font-weight: bold">if</span> k <span style="color: #666666">!=</span> i:
tmp <span style="color: #666666">*=</span> (n <span style="color: #666666">-</span> k)
f7_grad_analytical <span style="color: #666666">+=</span> tmp
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The analytical derivative of f7 at n = </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>(n,f7_grad_analytical))
</pre></div>
<p>
Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="unsupported-functions">Unsupported functions </h2>
Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.
<p>
Assigning a value to the variable being differentiated with respect to
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f8</span>(x): <span style="color: #408080; font-style: italic"># Assume x is an array</span>
x[<span style="color: #666666">2</span>] <span style="color: #666666">=</span> <span style="color: #666666">3</span>
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">*2</span>
f8_grad <span style="color: #666666">=</span> grad(f8)
x <span style="color: #666666">=</span> <span style="color: #666666">8.4</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The derivative of f8 is:&quot;</span>,f8_grad(x))
</pre></div>
<p>
Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-syntax-a-dot-b-when-finding-the-dot-product">The syntax a.dot(b) when finding the dot product </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f9</span>(a): <span style="color: #408080; font-style: italic"># Assume a is an array with 2 elements</span>
b <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">1.0</span>,<span style="color: #666666">2.0</span>])
<span style="color: #008000; font-weight: bold">return</span> a<span style="color: #666666">.</span>dot(b)
f9_grad <span style="color: #666666">=</span> grad(f9)
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">1.0</span>,<span style="color: #666666">0.0</span>])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The derivative of f9 is:&quot;</span>,f9_grad(x))
</pre></div>
<p>
Here we are told that the 'dot' function does not belong to Autograd's
version of a Numpy array. To overcome this, an alternative syntax
which also computed the dot product can be used:
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f9_alternative</span>(x): <span style="color: #408080; font-style: italic"># Assume a is an array with 2 elements</span>
b <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">1.0</span>,<span style="color: #666666">2.0</span>])
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>dot(x,b) <span style="color: #408080; font-style: italic"># The same as x_1*b_1 + x_2*b_2</span>
f9_alternative_grad <span style="color: #666666">=</span> grad(f9_alternative)
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">3.0</span>,<span style="color: #666666">0.0</span>])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The gradient of f9 is:&quot;</span>,f9_alternative_grad(x))
<span style="color: #408080; font-style: italic"># The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively</span>
<span style="color: #408080; font-style: italic"># w.r.t x is (b_1, b_2).</span>
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="recommended-to-avoid">Recommended to avoid </h2>
The documentation recommends to avoid inplace operations such as
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>a <span style="color: #666666">+=</span> b
a <span style="color: #666666">-=</span> b
a<span style="color: #666666">*=</span> b
a <span style="color: #666666">/=</span>b
</pre></div>
<p>
<!-- ------------------- end of main content --------------- -->
Binary file not shown.
+961 -4
View File
@@ -10,7 +10,7 @@
"<!-- Author: --> \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
"Date: **Sep 30, 2021**\n",
"Date: **Oct 1, 2021**\n",
"\n",
"Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
@@ -1893,9 +1893,9 @@
"\n",
"* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.\n",
"\n",
"## To be added\n",
"## Challenge yourself\n",
"\n",
"We will add here an example which computes the likelihood $p_i$, sets up the gradient and the Hessian matrix.\n",
"Write a code which implements gradient descent for a logistic regression example.\n",
"\n",
"\n",
"\n",
@@ -2198,7 +2198,964 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"**Challenge**: try to write a similar code for a Logistic Regression case."
"**Challenge**: try to write a similar code for a Logistic Regression case.\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Momentum based GD\n",
"\n",
"The stochastic gradient descent (SGD) is almost always used with a\n",
"*momentum* or inertia term that serves as a memory of the direction we\n",
"are moving in parameter space. This is typically implemented as\n",
"follows"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"_auto1\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \n",
"\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n",
"\\label{_auto1} \\tag{2}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where we have introduced a momentum parameter $\\gamma$, with\n",
"$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n",
"indicate the gradient is to be taken over a different mini-batch at\n",
"each step. We call this algorithm gradient descent with momentum\n",
"(GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a\n",
"running average of recently encountered gradients and\n",
"$(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory\n",
"used in the averaging procedure. Consistent with this, when\n",
"$\\gamma=0$, this just reduces down to ordinary SGD as discussed\n",
"earlier. An equivalent way of writing the updates is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$.\n",
"\n",
"## More on momentum based approaches\n",
"\n",
"Let us try to get more intuition from these equations. It is helpful\n",
"to consider a simple physical analogy with a particle of mass $m$\n",
"moving in a viscous medium with drag coefficient $\\mu$ and potential\n",
"$E(\\mathbf{w})$. If we denote the particle's position by $\\mathbf{w}$,\n",
"then its motion is described by"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m {d^2 \\mathbf{w} \\over dt^2} + \\mu {d \\mathbf{w} \\over dt }= -\\nabla_w E(\\mathbf{w}).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can discretize this equation in the usual way to get"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m { \\mathbf{w}_{t+\\Delta t}-2 \\mathbf{w}_{t} +\\mathbf{w}_{t-\\Delta t} \\over (\\Delta t)^2}+\\mu {\\mathbf{w}_{t+\\Delta t}- \\mathbf{w}_{t} \\over \\Delta t} = -\\nabla_w E(\\mathbf{w}).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Rearranging this equation, we can rewrite this as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Delta \\mathbf{w}_{t +\\Delta t}= - { (\\Delta t)^2 \\over m +\\mu \\Delta t} \\nabla_w E(\\mathbf{w})+ {m \\over m +\\mu \\Delta t} \\Delta \\mathbf{w}_t.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Momentum parameter\n",
"\n",
"Notice that this equation is identical to previous one if we identify\n",
"the position of the particle, $\\mathbf{w}$, with the parameters\n",
"$\\boldsymbol{\\theta}$. This allows us to identify the momentum\n",
"parameter and learning rate with the mass of the particle and the\n",
"viscous drag as:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Thus, as the name suggests, the momentum parameter is proportional to\n",
"the mass of the particle and effectively provides inertia.\n",
"Furthermore, in the large viscosity/small learning rate limit, our\n",
"memory time scales as $(1-\\gamma)^{-1} \\approx m/(\\mu \\Delta t)$.\n",
"\n",
"Why is momentum useful? SGD momentum helps the gradient descent\n",
"algorithm gain speed in directions with persistent but small gradients\n",
"even in the presence of stochasticity, while suppressing oscillations\n",
"in high-curvature directions. This becomes especially important in\n",
"situations where the landscape is shallow and flat in some directions\n",
"and narrow and steep in others. It has been argued that first-order\n",
"methods (with appropriate initial conditions) can perform comparable\n",
"to more expensive second order methods, especially in the context of\n",
"complex deep learning models.\n",
"\n",
"These beneficial properties of momentum can sometimes become even more\n",
"pronounced by using a slight modification of the classical momentum\n",
"algorithm called Nesterov Accelerated Gradient (NAG).\n",
"\n",
"In the NAG algorithm, rather than calculating the gradient at the\n",
"current parameters, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t)$, one\n",
"calculates the gradient at the expected value of the parameters given\n",
"our current momentum, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma\n",
"\\mathbf{v}_{t-1})$. This yields the NAG update rule"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1}) \\nonumber\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"_auto2\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \n",
"\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t}.\n",
"\\label{_auto2} \\tag{3}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\\gamma$.\n",
"\n",
"\n",
"## Second moment of the gradient\n",
"\n",
"\n",
"In stochastic gradient descent, with and without momentum, we still\n",
"have to specify a schedule for tuning the learning rates $\\eta_t$\n",
"as a function of time. As discussed in the context of Newton's\n",
"method, this presents a number of dilemmas. The learning rate is\n",
"limited by the steepest direction which can change depending on the\n",
"current position in the landscape. To circumvent this problem, ideally\n",
"our algorithm would keep track of curvature and take large steps in\n",
"shallow, flat directions and small steps in steep, narrow directions.\n",
"Second-order methods accomplish this by calculating or approximating\n",
"the Hessian and normalizing the learning rate by the\n",
"curvature. However, this is very computationally expensive for\n",
"extremely large models. Ideally, we would like to be able to\n",
"adaptively change the step size to match the landscape without paying\n",
"the steep computational price of calculating or approximating\n",
"Hessians.\n",
"\n",
"Recently, a number of methods have been introduced that accomplish\n",
"this by tracking not only the gradient, but also the second moment of\n",
"the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and\n",
"ADAM.\n",
"\n",
"## RMS prop\n",
"\n",
"In RMS prop, in addition to keeping a running average of the first\n",
"moment of the gradient, we also keep track of the second moment\n",
"denoted by $\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}_t^2]$. The update rule\n",
"for RMS prop is given by"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"_auto3\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
"\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n",
"\\label{_auto3} \\tag{4}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\mathbf{g}_t \\over \\sqrt{\\mathbf{s}_t +\\epsilon}}, \\nonumber\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\beta$ controls the averaging time of the second moment and is\n",
"typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate\n",
"typically chosen to be $10^{-3}$, and $\\epsilon\\sim 10^{-8} $ is a\n",
"small regularization constant to prevent divergences. Multiplication\n",
"and division by vectors is understood as an element-wise operation. It\n",
"is clear from this formula that the learning rate is reduced in\n",
"directions where the norm of the gradient is consistently large. This\n",
"greatly speeds up the convergence by allowing us to use a larger\n",
"learning rate for flat directions.\n",
"\n",
"\n",
"## ADAM optimizer\n",
"\n",
"A related algorithm is the ADAM optimizer. In ADAM, we keep a running\n",
"average of both the first and second moment of the gradient and use\n",
"this information to adaptively change the learning rate for different\n",
"parameters. In addition to keeping a running average of the first and\n",
"second moments of the gradient\n",
"(i.e. $\\mathbf{m}_t=\\mathbb{E}[\\mathbf{g}_t]$ and\n",
"$\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}^2_t]$, respectively), ADAM\n",
"performs an additional bias correction to account for the fact that we\n",
"are estimating the first two moments of the gradient using a running\n",
"average (denoted by the hats in the update rule below). The update\n",
"rule for ADAM is given by (where multiplication and division are once\n",
"again understood to be element-wise operations below)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"_auto4\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
"\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n",
"\\label{_auto4} \\tag{5}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\boldsymbol{\\mathbf{m}}_t \\over \\sqrt{\\boldsymbol{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"_auto5\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \n",
"\\label{_auto5} \\tag{6}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and\n",
"second moment and are typically taken to be $0.9$ and $0.99$\n",
"respectively, and $\\eta$ and $\\epsilon$ are identical to RMSprop.\n",
"\n",
"Like in RMSprop, the effective step size of a parameter depends on the\n",
"magnitude of its gradient squared. To understand this better, let us\n",
"rewrite this expression in terms of the variance\n",
"$\\boldsymbol{\\sigma}_t^2 = \\boldsymbol{\\mathbf{s}}_t -\n",
"(\\boldsymbol{\\mathbf{m}}_t)^2$. Consider a single parameter $\\theta_t$. The\n",
"update rule for this parameter is given by"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Delta \\theta_{t+1}= -\\eta_t { \\boldsymbol{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Practical tips\n",
"\n",
"* **Randomize the data when making mini-batches**. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.\n",
"\n",
"* **Transform your inputs**. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.\n",
"\n",
"* **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.\n",
"\n",
"* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.\n",
"\n",
"Geron's text, see chapter 11, has several interesting discussions.\n",
"\n",
"\n",
"\n",
"## Automatic differentiation\n",
"\n",
"[Automatic differentiation (AD)](https://en.wikipedia.org/wiki/Automatic_differentiation), \n",
"also called algorithmic\n",
"differentiation or computational differentiation,is a set of\n",
"techniques to numerically evaluate the derivative of a function\n",
"specified by a computer program. AD exploits the fact that every\n",
"computer program, no matter how complicated, executes a sequence of\n",
"elementary arithmetic operations (addition, subtraction,\n",
"multiplication, division, etc.) and elementary functions (exp, log,\n",
"sin, cos, etc.). By applying the chain rule repeatedly to these\n",
"operations, derivatives of arbitrary order can be computed\n",
"automatically, accurately to working precision, and using at most a\n",
"small constant factor more arithmetic operations than the original\n",
"program.\n",
"\n",
"Automatic differentiation is neither:\n",
"\n",
"* Symbolic differentiation, nor\n",
"\n",
"* Numerical differentiation (the method of finite differences).\n",
"\n",
"Symbolic differentiation can lead to inefficient code and faces the\n",
"difficulty of converting a computer program into a single expression,\n",
"while numerical differentiation can introduce round-off errors in the\n",
"discretization process and cancellation\n",
"\n",
"\n",
"\n",
"Python has tools for so-called **automatic differentiation**.\n",
"Consider the following example"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"f(x) = \\sin\\left(2\\pi x + x^2\\right)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which has the following derivative"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"f'(x) = \\cos\\left(2\\pi x + x^2\\right)\\left(2\\pi + 2x\\right)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using **autograd** we have"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"\n",
"# To do elementwise differentiation:\n",
"from autograd import elementwise_grad as egrad \n",
"\n",
"# To plot:\n",
"import matplotlib.pyplot as plt \n",
"\n",
"\n",
"def f(x):\n",
" return np.sin(2*np.pi*x + x**2)\n",
"\n",
"def f_grad_analytic(x):\n",
" return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)\n",
"\n",
"# Do the comparison:\n",
"x = np.linspace(0,1,1000)\n",
"\n",
"f_grad = egrad(f)\n",
"\n",
"computed = f_grad(x)\n",
"analytic = f_grad_analytic(x)\n",
"\n",
"plt.title('Derivative computed from Autograd compared with the analytical derivative')\n",
"plt.plot(x,computed,label='autograd')\n",
"plt.plot(x,analytic,label='analytic')\n",
"\n",
"plt.xlabel('x')\n",
"plt.ylabel('y')\n",
"plt.legend()\n",
"\n",
"plt.show()\n",
"\n",
"print(\"The max absolute difference is: %g\"%(np.max(np.abs(computed - analytic))))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- !split -->\n",
"## Using autograd\n",
"\n",
"Here we\n",
"experiment with what kind of functions Autograd is capable\n",
"of finding the gradient of. The following Python functions are just\n",
"meant to illustrate what Autograd can do, but please feel free to\n",
"experiment with other, possibly more complicated, functions as well."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"\n",
"def f1(x):\n",
" return x**3 + 1\n",
"\n",
"f1_grad = grad(f1)\n",
"\n",
"# Remember to send in float as argument to the computed gradient from Autograd!\n",
"a = 1.0\n",
"\n",
"# See the evaluated gradient at a using autograd:\n",
"print(\"The gradient of f1 evaluated at a = %g using autograd is: %g\"%(a,f1_grad(a)))\n",
"\n",
"# Compare with the analytical derivative, that is f1'(x) = 3*x**2 \n",
"grad_analytical = 3*a**2\n",
"print(\"The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g\"%(a,grad_analytical))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Autograd with more complicated functions\n",
"\n",
"To differentiate with respect to two (or more) arguments of a Python\n",
"function, Autograd need to know at which variable the function if\n",
"being differentiated with respect to."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"def f2(x1,x2):\n",
" return 3*x1**3 + x2*(x1 - 5) + 1\n",
"\n",
"# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1\n",
"f2_grad_x1 = grad(f2,0)\n",
"\n",
"# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad\n",
"f2_grad_x2 = grad(f2,1)\n",
"\n",
"x1 = 1.0\n",
"x2 = 3.0 \n",
"\n",
"print(\"Evaluating at x1 = %g, x2 = %g\"%(x1,x2))\n",
"print(\"-\"*30)\n",
"\n",
"# Compare with the analytical derivatives:\n",
"\n",
"# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:\n",
"f2_grad_x1_analytical = 9*x1**2 + x2\n",
"\n",
"# Derivative of f2 w.r.t x2 is: x1 - 5:\n",
"f2_grad_x2_analytical = x1 - 5\n",
"\n",
"# See the evaluated derivations:\n",
"print(\"The derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n",
"print(\"The analytical derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n",
"\n",
"print()\n",
"\n",
"print(\"The derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))\n",
"print(\"The analytical derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.\n",
"\n",
"\n",
"## More complicated functions using the elements of their arguments directly"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"def f3(x): # Assumes x is an array of length 5 or higher\n",
" return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2\n",
"\n",
"f3_grad = grad(f3)\n",
"\n",
"x = np.linspace(0,4,5)\n",
"\n",
"# Print the computed gradient:\n",
"print(\"The computed gradient of f3 is: \", f3_grad(x))\n",
"\n",
"# The analytical gradient is: (2, 3, 5, 7, 22*x[4])\n",
"f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])\n",
"\n",
"# Print the analytical gradient:\n",
"print(\"The analytical gradient of f3 is: \", f3_grad_analytical)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that in this case, when sending an array as input argument, the\n",
"output from Autograd is another array. This is the true gradient of\n",
"the function, as opposed to the function in the previous example. By\n",
"using arrays to represent the variables, the output from Autograd\n",
"might be easier to work with, as the output is closer to what one\n",
"could expect form a gradient-evaluting function.\n",
"\n",
"<!-- !split -->\n",
"## Functions using mathematical functions from Numpy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"def f4(x):\n",
" return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)\n",
"\n",
"f4_grad = grad(f4)\n",
"\n",
"x = 2.7\n",
"\n",
"# Print the computed derivative:\n",
"print(\"The computed derivative of f4 at x = %g is: %g\"%(x,f4_grad(x)))\n",
"\n",
"# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi\n",
"f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi\n",
"\n",
"# Print the analytical gradient:\n",
"print(\"The analytical gradient of f4 at x = %g is: %g\"%(x,f4_grad_analytical))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## More autograd"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"def f5(x):\n",
" if x >= 0:\n",
" return x**2\n",
" else:\n",
" return -3*x + 1\n",
"\n",
"f5_grad = grad(f5)\n",
"\n",
"x = 2.7\n",
"\n",
"# Print the computed derivative:\n",
"print(\"The computed derivative of f5 at x = %g is: %g\"%(x,f5_grad(x)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## And with loops"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2\n",
"1\n",
" \n",
"<\n",
"<\n",
"<\n",
"!\n",
"!\n",
"C\n",
"O\n",
"D\n",
"E\n",
"_\n",
"B\n",
"L\n",
"O\n",
"C\n",
"K\n",
" \n",
" \n",
"p\n",
"y\n",
"c\n",
"o\n",
"d"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9\n",
"# The analytical derivative is: sum(i*x**(i-1)) \n",
"f6_grad_analytical = 0\n",
"for i in range(10):\n",
" f6_grad_analytical += i*x**(i-1)\n",
"\n",
"print(\"The analytical derivative of f6 at x = %g is: %g\"%(x,f6_grad_analytical))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using recursion"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"\n",
"def f7(n): # Assume that n is an integer\n",
" if n == 1 or n == 0:\n",
" return 1\n",
" else:\n",
" return n*f7(n-1)\n",
"\n",
"f7_grad = grad(f7)\n",
"\n",
"n = 2.0\n",
"\n",
"print(\"The computed derivative of f7 at n = %d is: %g\"%(n,f7_grad(n)))\n",
"\n",
"# The function f7 is an implementation of the factorial of n.\n",
"# By using the product rule, one can find that the derivative is:\n",
"\n",
"f7_grad_analytical = 0\n",
"for i in range(int(n)-1):\n",
" tmp = 1\n",
" for k in range(int(n)-1):\n",
" if k != i:\n",
" tmp *= (n - k)\n",
" f7_grad_analytical += tmp\n",
"\n",
"print(\"The analytical derivative of f7 at n = %d is: %g\"%(n,f7_grad_analytical))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.\n",
"\n",
"## Unsupported functions\n",
"Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.\n",
"\n",
"Assigning a value to the variable being differentiated with respect to"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"def f8(x): # Assume x is an array\n",
" x[2] = 3\n",
" return x*2\n",
"\n",
"f8_grad = grad(f8)\n",
"\n",
"x = 8.4\n",
"\n",
"print(\"The derivative of f8 is:\",f8_grad(x))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.\n",
"\n",
"## The syntax a.dot(b) when finding the dot product"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"def f9(a): # Assume a is an array with 2 elements\n",
" b = np.array([1.0,2.0])\n",
" return a.dot(b)\n",
"\n",
"f9_grad = grad(f9)\n",
"\n",
"x = np.array([1.0,0.0])\n",
"\n",
"print(\"The derivative of f9 is:\",f9_grad(x))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we are told that the 'dot' function does not belong to Autograd's\n",
"version of a Numpy array. To overcome this, an alternative syntax\n",
"which also computed the dot product can be used:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad\n",
"def f9_alternative(x): # Assume a is an array with 2 elements\n",
" b = np.array([1.0,2.0])\n",
" return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2\n",
"\n",
"f9_alternative_grad = grad(f9_alternative)\n",
"\n",
"x = np.array([3.0,0.0])\n",
"\n",
"print(\"The gradient of f9 is:\",f9_alternative_grad(x))\n",
"\n",
"# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively\n",
"# w.r.t x is (b_1, b_2)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Recommended to avoid\n",
"The documentation recommends to avoid inplace operations such as"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"a += b\n",
"a -= b\n",
"a*= b\n",
"a /=b"
]
}
],
+608 -2
View File
@@ -1232,9 +1232,9 @@ plt.show()
!split
===== To be added =====
===== Challenge yourself =====
We will add here an example which computes the likelihood $p_i$, sets up the gradient and the Hessian matrix.
Write a code which implements gradient descent for a logistic regression example.
@@ -1481,3 +1481,609 @@ _Challenge_: try to write a similar code for a Logistic Regression case.
!split
===== Momentum based GD =====
The stochastic gradient descent (SGD) is almost always used with a
*momentum* or inertia term that serves as a memory of the direction we
are moving in parameter space. This is typically implemented as
follows
!bt
\begin{align}
\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\
\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t},
\end{align}
!et
where we have introduced a momentum parameter $\gamma$, with
$0\le\gamma\le 1$, and for brevity we dropped the explicit notation to
indicate the gradient is to be taken over a different mini-batch at
each step. We call this algorithm gradient descent with momentum
(GDM). From these equations, it is clear that $\mathbf{v}_t$ is a
running average of recently encountered gradients and
$(1-\gamma)^{-1}$ sets the characteristic time scale for the memory
used in the averaging procedure. Consistent with this, when
$\gamma=0$, this just reduces down to ordinary SGD as discussed
earlier. An equivalent way of writing the updates is
!bt
\[
\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t),
\]
!et
where we have defined $\Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1}$.
!split
===== More on momentum based approaches =====
Let us try to get more intuition from these equations. It is helpful
to consider a simple physical analogy with a particle of mass $m$
moving in a viscous medium with drag coefficient $\mu$ and potential
$E(\mathbf{w})$. If we denote the particle's position by $\mathbf{w}$,
then its motion is described by
!bt
\[
m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}).
\]
!et
We can discretize this equation in the usual way to get
!bt
\[
m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}).
\]
!et
Rearranging this equation, we can rewrite this as
!bt
\[
\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t.
\]
!et
!split
===== Momentum parameter =====
Notice that this equation is identical to previous one if we identify
the position of the particle, $\mathbf{w}$, with the parameters
$\boldsymbol{\theta}$. This allows us to identify the momentum
parameter and learning rate with the mass of the particle and the
viscous drag as:
!bt
\[
\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}.
\]
!et
Thus, as the name suggests, the momentum parameter is proportional to
the mass of the particle and effectively provides inertia.
Furthermore, in the large viscosity/small learning rate limit, our
memory time scales as $(1-\gamma)^{-1} \approx m/(\mu \Delta t)$.
Why is momentum useful? SGD momentum helps the gradient descent
algorithm gain speed in directions with persistent but small gradients
even in the presence of stochasticity, while suppressing oscillations
in high-curvature directions. This becomes especially important in
situations where the landscape is shallow and flat in some directions
and narrow and steep in others. It has been argued that first-order
methods (with appropriate initial conditions) can perform comparable
to more expensive second order methods, especially in the context of
complex deep learning models.
These beneficial properties of momentum can sometimes become even more
pronounced by using a slight modification of the classical momentum
algorithm called Nesterov Accelerated Gradient (NAG).
In the NAG algorithm, rather than calculating the gradient at the
current parameters, $\nabla_\theta E(\boldsymbol{\theta}_t)$, one
calculates the gradient at the expected value of the parameters given
our current momentum, $\nabla_\theta E(\boldsymbol{\theta}_t +\gamma
\mathbf{v}_{t-1})$. This yields the NAG update rule
!bt
\begin{align}
\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\
\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}.
\end{align}
!et
One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\gamma$.
!split
===== Second moment of the gradient =====
In stochastic gradient descent, with and without momentum, we still
have to specify a schedule for tuning the learning rates $\eta_t$
as a function of time. As discussed in the context of Newton's
method, this presents a number of dilemmas. The learning rate is
limited by the steepest direction which can change depending on the
current position in the landscape. To circumvent this problem, ideally
our algorithm would keep track of curvature and take large steps in
shallow, flat directions and small steps in steep, narrow directions.
Second-order methods accomplish this by calculating or approximating
the Hessian and normalizing the learning rate by the
curvature. However, this is very computationally expensive for
extremely large models. Ideally, we would like to be able to
adaptively change the step size to match the landscape without paying
the steep computational price of calculating or approximating
Hessians.
Recently, a number of methods have been introduced that accomplish
this by tracking not only the gradient, but also the second moment of
the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and
ADAM.
!split
===== RMS prop =====
In RMS prop, in addition to keeping a running average of the first
moment of the gradient, we also keep track of the second moment
denoted by $\mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2]$. The update rule
for RMS prop is given by
!bt
\begin{align}
\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) \\
\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\
\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber
\end{align}
!et
where $\beta$ controls the averaging time of the second moment and is
typically taken to be about $\beta=0.9$, $\eta_t$ is a learning rate
typically chosen to be $10^{-3}$, and $\epsilon\sim 10^{-8} $ is a
small regularization constant to prevent divergences. Multiplication
and division by vectors is understood as an element-wise operation. It
is clear from this formula that the learning rate is reduced in
directions where the norm of the gradient is consistently large. This
greatly speeds up the convergence by allowing us to use a larger
learning rate for flat directions.
!split
===== ADAM optimizer =====
A related algorithm is the ADAM optimizer. In ADAM, we keep a running
average of both the first and second moment of the gradient and use
this information to adaptively change the learning rate for different
parameters. In addition to keeping a running average of the first and
second moments of the gradient
(i.e. $\mathbf{m}_t=\mathbb{E}[\mathbf{g}_t]$ and
$\mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t]$, respectively), ADAM
performs an additional bias correction to account for the fact that we
are estimating the first two moments of the gradient using a running
average (denoted by the hats in the update rule below). The update
rule for ADAM is given by (where multiplication and division are once
again understood to be element-wise operations below)
!bt
\begin{align}
\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) \\
\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\
\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\
\bm{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\
\bm{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\
\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \bm{\mathbf{m}}_t \over \sqrt{\bm{\mathbf{s}}_t} +\epsilon}, \nonumber \\
\end{align}
!et
where $\beta_1$ and $\beta_2$ set the memory lifetime of the first and
second moment and are typically taken to be $0.9$ and $0.99$
respectively, and $\eta$ and $\epsilon$ are identical to RMSprop.
Like in RMSprop, the effective step size of a parameter depends on the
magnitude of its gradient squared. To understand this better, let us
rewrite this expression in terms of the variance
$\boldsymbol{\sigma}_t^2 = \bm{\mathbf{s}}_t -
(\bm{\mathbf{m}}_t)^2$. Consider a single parameter $\theta_t$. The
update rule for this parameter is given by
!bt
\[
\Delta \theta_{t+1}= -\eta_t { \bm{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}.
\]
!et
!split
===== Practical tips =====
* _Randomize the data when making mini-batches_. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.
* _Transform your inputs_. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.
* _Monitor the out-of-sample performance._ Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.
* _Adaptive optimization methods don't always have good generalization._ Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.
Geron's text, see chapter 11, has several interesting discussions.
!split
===== Automatic differentiation =====
"Automatic differentiation (AD)":"https://en.wikipedia.org/wiki/Automatic_differentiation",
also called algorithmic
differentiation or computational differentiation,is a set of
techniques to numerically evaluate the derivative of a function
specified by a computer program. AD exploits the fact that every
computer program, no matter how complicated, executes a sequence of
elementary arithmetic operations (addition, subtraction,
multiplication, division, etc.) and elementary functions (exp, log,
sin, cos, etc.). By applying the chain rule repeatedly to these
operations, derivatives of arbitrary order can be computed
automatically, accurately to working precision, and using at most a
small constant factor more arithmetic operations than the original
program.
Automatic differentiation is neither:
* Symbolic differentiation, nor
* Numerical differentiation (the method of finite differences).
Symbolic differentiation can lead to inefficient code and faces the
difficulty of converting a computer program into a single expression,
while numerical differentiation can introduce round-off errors in the
discretization process and cancellation
Python has tools for so-called _automatic differentiation_.
Consider the following example
!bt
\[
f(x) = \sin\left(2\pi x + x^2\right)
\]
!et
which has the following derivative
!bt
\[
f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right)
\]
!et
Using _autograd_ we have
!bc pycod
import autograd.numpy as np
# To do elementwise differentiation:
from autograd import elementwise_grad as egrad
# To plot:
import matplotlib.pyplot as plt
def f(x):
return np.sin(2*np.pi*x + x**2)
def f_grad_analytic(x):
return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)
# Do the comparison:
x = np.linspace(0,1,1000)
f_grad = egrad(f)
computed = f_grad(x)
analytic = f_grad_analytic(x)
plt.title('Derivative computed from Autograd compared with the analytical derivative')
plt.plot(x,computed,label='autograd')
plt.plot(x,analytic,label='analytic')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
!ec
!split
===== Using autograd =====
Here we
experiment with what kind of functions Autograd is capable
of finding the gradient of. The following Python functions are just
meant to illustrate what Autograd can do, but please feel free to
experiment with other, possibly more complicated, functions as well.
!bc pycod
import autograd.numpy as np
from autograd import grad
def f1(x):
return x**3 + 1
f1_grad = grad(f1)
# Remember to send in float as argument to the computed gradient from Autograd!
a = 1.0
# See the evaluated gradient at a using autograd:
print("The gradient of f1 evaluated at a = %g using autograd is: %g"%(a,f1_grad(a)))
# Compare with the analytical derivative, that is f1'(x) = 3*x**2
grad_analytical = 3*a**2
print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical))
!ec
!split
===== Autograd with more complicated functions =====
To differentiate with respect to two (or more) arguments of a Python
function, Autograd need to know at which variable the function if
being differentiated with respect to.
!bc pycod
import autograd.numpy as np
from autograd import grad
def f2(x1,x2):
return 3*x1**3 + x2*(x1 - 5) + 1
# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1
f2_grad_x1 = grad(f2,0)
# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad
f2_grad_x2 = grad(f2,1)
x1 = 1.0
x2 = 3.0
print("Evaluating at x1 = %g, x2 = %g"%(x1,x2))
print("-"*30)
# Compare with the analytical derivatives:
# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:
f2_grad_x1_analytical = 9*x1**2 + x2
# Derivative of f2 w.r.t x2 is: x1 - 5:
f2_grad_x2_analytical = x1 - 5
# See the evaluated derivations:
print("The derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
print("The analytical derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
print()
print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
!ec
Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.
!split
===== More complicated functions using the elements of their arguments directly =====
!bc pycod
import autograd.numpy as np
from autograd import grad
def f3(x): # Assumes x is an array of length 5 or higher
return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
f3_grad = grad(f3)
x = np.linspace(0,4,5)
# Print the computed gradient:
print("The computed gradient of f3 is: ", f3_grad(x))
# The analytical gradient is: (2, 3, 5, 7, 22*x[4])
f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])
# Print the analytical gradient:
print("The analytical gradient of f3 is: ", f3_grad_analytical)
!ec
Note that in this case, when sending an array as input argument, the
output from Autograd is another array. This is the true gradient of
the function, as opposed to the function in the previous example. By
using arrays to represent the variables, the output from Autograd
might be easier to work with, as the output is closer to what one
could expect form a gradient-evaluting function.
!split
===== Functions using mathematical functions from Numpy =====
!bc pycod
import autograd.numpy as np
from autograd import grad
def f4(x):
return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
f4_grad = grad(f4)
x = 2.7
# Print the computed derivative:
print("The computed derivative of f4 at x = %g is: %g"%(x,f4_grad(x)))
# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi
f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi
# Print the analytical gradient:
print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical))
!ec
!split
===== More autograd =====
!bc pycod
import autograd.numpy as np
from autograd import grad
def f5(x):
if x >= 0:
return x**2
else:
return -3*x + 1
f5_grad = grad(f5)
x = 2.7
# Print the computed derivative:
print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
!ec
!split
===== And with loops =====
!bc pycod
import autograd.numpy as np
from autograd import grad
def f6_for(x):
val = 0
for i in range(10):
val = val + x**i
return val
def f6_while(x):
val = 0
i = 0
while i < 10:
val = val + x**i
i = i + 1
return val
f6_for_grad = grad(f6_for)
f6_while_grad = grad(f6_while)
x = 0.5
# Print the computed derivaties of f6_for and f6_while
print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
!ec
!bc pycod
import autograd.numpy as np
from autograd import grad
# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
# The analytical derivative is: sum(i*x**(i-1))
f6_grad_analytical = 0
for i in range(10):
f6_grad_analytical += i*x**(i-1)
print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
!ec
!split
===== Using recursion =====
!bc pycod
import autograd.numpy as np
from autograd import grad
def f7(n): # Assume that n is an integer
if n == 1 or n == 0:
return 1
else:
return n*f7(n-1)
f7_grad = grad(f7)
n = 2.0
print("The computed derivative of f7 at n = %d is: %g"%(n,f7_grad(n)))
# The function f7 is an implementation of the factorial of n.
# By using the product rule, one can find that the derivative is:
f7_grad_analytical = 0
for i in range(int(n)-1):
tmp = 1
for k in range(int(n)-1):
if k != i:
tmp *= (n - k)
f7_grad_analytical += tmp
print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
!ec
Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.
!split
===== Unsupported functions =====
Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.
Assigning a value to the variable being differentiated with respect to
!bc pycod
import autograd.numpy as np
from autograd import grad
def f8(x): # Assume x is an array
x[2] = 3
return x*2
f8_grad = grad(f8)
x = 8.4
print("The derivative of f8 is:",f8_grad(x))
!ec
Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.
!split
===== The syntax a.dot(b) when finding the dot product =====
!bc pycod
import autograd.numpy as np
from autograd import grad
def f9(a): # Assume a is an array with 2 elements
b = np.array([1.0,2.0])
return a.dot(b)
f9_grad = grad(f9)
x = np.array([1.0,0.0])
print("The derivative of f9 is:",f9_grad(x))
!ec
Here we are told that the 'dot' function does not belong to Autograd's
version of a Numpy array. To overcome this, an alternative syntax
which also computed the dot product can be used:
!bc pycod
import autograd.numpy as np
from autograd import grad
def f9_alternative(x): # Assume a is an array with 2 elements
b = np.array([1.0,2.0])
return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2
f9_alternative_grad = grad(f9_alternative)
x = np.array([3.0,0.0])
print("The gradient of f9 is:",f9_alternative_grad(x))
# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively
# w.r.t x is (b_1, b_2).
!ec
!split
===== Recommended to avoid =====
The documentation recommends to avoid inplace operations such as
!bc pycod
a += b
a -= b
a*= b
a /=b
!ec