diff --git a/doc/pub/week39/html/week39-bs.html b/doc/pub/week39/html/week39-bs.html index 27c968c67..962307c78 100644 --- a/doc/pub/week39/html/week39-bs.html +++ b/doc/pub/week39/html/week39-bs.html @@ -178,46 +178,10 @@ doconce format html week39.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'program-for-stochastic-gradient'), - ('Momentum based GD', 2, None, 'momentum-based-gd'), - ('More on momentum based approaches', + ('Code with a Number of Minibatches which varies', 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')]} + 'code-with-a-number-of-minibatches-which-varies')]} end of tocinfo --> @@ -309,24 +273,7 @@ MathJax.Hub.Config({
  • When do we stop?
  • Slightly different approach
  • Program for stochastic gradient
  • -
  • Momentum based GD
  • -
  • More on momentum based approaches
  • -
  • Momentum parameter
  • -
  • Second moment of the gradient
  • -
  • RMS prop
  • -
  • ADAM optimizer
  • -
  • Practical tips
  • -
  • Automatic differentiation
  • -
  • Using autograd
  • -
  • Autograd with more complicated functions
  • -
  • More complicated functions using the elements of their arguments directly
  • -
  • Functions using mathematical functions from Numpy
  • -
  • More autograd
  • -
  • And with loops
  • -
  • Using recursion
  • -
  • Unsupported functions
  • -
  • The syntax a.dot(b) when finding the dot product
  • -
  • Recommended to avoid
  • +
  • Code with a Number of Minibatches which varies
  • @@ -381,7 +328,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 76
  • +
  • 59
  • »
  • diff --git a/doc/pub/week39/html/week39-reveal.html b/doc/pub/week39/html/week39-reveal.html index c5f0e3dd7..7271e8515 100644 --- a/doc/pub/week39/html/week39-reveal.html +++ b/doc/pub/week39/html/week39-reveal.html @@ -2188,883 +2188,81 @@ plt.show()
    -

    Momentum based GD

    +

    Code with a Number of Minibatches which varies

    -

    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 -

    +

    In the code here we vary the number of mini-batches.

    -

     
    -$$ -\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} -$$ -

     
    - -

    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} \).

    -
    - -
    -

    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 -

    - -

     
    -$$ -m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). -$$ -

     
    - -

    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}). -$$ -

     
    - -

    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. -$$ -

     
    -

    - -
    -

    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: -

    - -

     
    -$$ -\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. -$$ -

     
    - -

    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 -

    - -

     
    -$$ -\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} -$$ -

     
    - -

    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 \).

    -
    - -
    -

    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. -

    -
    - -
    -

    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 -

    - -

     
    -$$ -\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} -$$ -

     
    - -

    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. -

    -
    - -
    -

    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) -

    - -

     
    -$$ -\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} -$$ -

     
    - -

    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 = \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}. -$$ -

     
    -

    - -
    -

    Practical tips

    - - -

    -

    Geron's text, see chapter 11, has several interesting discussions.

    -
    - -
    -

    Automatic differentiation

    - -

    Automatic differentiation (AD), -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 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 -

    -

     
    -$$ -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 autograd we have

    - - - +
    -
    import autograd.numpy as np
    +  
    # Importing various packages
    +from math import exp, sqrt
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
     
    -# To do elementwise differentiation:
    -from autograd import elementwise_grad as egrad 
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
     
    -# To plot:
    -import matplotlib.pyplot as plt 
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
     
     
    -def f(x):
    -    return np.sin(2*np.pi*x + x**2)
    +for iter in range(Niterations):
    +    gradients = 2.0/n*X.T @ ((X @ theta)-y)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
     
    -def f_grad_analytic(x):
    -    return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
     
    -# Do the comparison:
    -x = np.linspace(0,1,1000)
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
     
    -f_grad = egrad(f)
    +theta = np.random.randn(2,1)
     
    -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()
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = np.random.randint(m)
    +        xi = X[random_index*M:random_index*M+M]
    +        yi = y[random_index*M:random_index*M+M]
    +        gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
     
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
     plt.show()
    -
    -print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    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. -

    - - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    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. -

    - - - -
    -
    -
    -
    -
    -
    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) ))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    -
    - -
    -

    More complicated functions using the elements of their arguments directly

    - - - -
    -
    -
    -
    -
    -
    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)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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. -

    -
    - -
    -

    Functions using mathematical functions from Numpy

    - - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    More autograd

    - - - -
    -
    -
    -
    -
    -
    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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    And with loops

    - - - -
    -
    -
    -
    -
    -
    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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Using recursion

    - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    -
    - -
    -

    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

    - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    -
    - -
    -

    The syntax a.dot(b) when finding the dot product

    - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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: -

    - - - -
    -
    -
    -
    -
    -
    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).
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - -

    The documentation recommends to avoid inplace operations such as

    - - -
    -
    -
    -
    -
    -
    a += b
    -a -= b
    -a*= b
    -a /=b
     
    diff --git a/doc/pub/week39/html/week39-solarized.html b/doc/pub/week39/html/week39-solarized.html index 01032d649..4ad4e500f 100644 --- a/doc/pub/week39/html/week39-solarized.html +++ b/doc/pub/week39/html/week39-solarized.html @@ -205,46 +205,10 @@ div.toc p,a { 2, None, 'program-for-stochastic-gradient'), - ('Momentum based GD', 2, None, 'momentum-based-gd'), - ('More on momentum based approaches', + ('Code with a Number of Minibatches which varies', 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')]} + 'code-with-a-number-of-minibatches-which-varies')]} end of tocinfo --> @@ -2111,848 +2075,81 @@ plt.show()

    Challenge: try to write a similar code for a Logistic Regression case.











    -

    Momentum based GD

    +

    Code with a Number of Minibatches which varies

    -

    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 -

    +

    In the code here we vary the number of mini-batches.

    -$$ -\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} -$$ - -

    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} \).

    - -









    -

    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 -

    - -$$ -m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). -$$ - -

    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}). -$$ - -

    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. -$$ - - -









    -

    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: -

    - -$$ -\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. -$$ - -

    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 -

    - -$$ -\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} -$$ - -

    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 \).

    - -









    -

    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. -

    - -









    -

    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 -

    - -$$ -\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} -$$ - -

    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. -

    - -









    -

    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) -

    - -$$ -\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} -$$ - -

    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 = \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}. -$$ - - -









    -

    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.

    - -









    -

    Automatic differentiation

    - -

    Automatic differentiation (AD), -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 -

    -$$ -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 autograd we have

    - - - +
    -
    import autograd.numpy as np
    +  
    # Importing various packages
    +from math import exp, sqrt
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
     
    -# To do elementwise differentiation:
    -from autograd import elementwise_grad as egrad 
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
     
    -# To plot:
    -import matplotlib.pyplot as plt 
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
     
     
    -def f(x):
    -    return np.sin(2*np.pi*x + x**2)
    +for iter in range(Niterations):
    +    gradients = 2.0/n*X.T @ ((X @ theta)-y)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
     
    -def f_grad_analytic(x):
    -    return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
     
    -# Do the comparison:
    -x = np.linspace(0,1,1000)
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
     
    -f_grad = egrad(f)
    +theta = np.random.randn(2,1)
     
    -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()
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = np.random.randint(m)
    +        xi = X[random_index*M:random_index*M+M]
    +        yi = y[random_index*M:random_index*M+M]
    +        gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
     
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
     plt.show()
    -
    -print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    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. -

    - - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    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. -

    - - - -
    -
    -
    -
    -
    -
    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) ))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    - -









    -

    More complicated functions using the elements of their arguments directly

    - - - -
    -
    -
    -
    -
    -
    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)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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. -

    - - -

    Functions using mathematical functions from Numpy

    - - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    More autograd

    - - - -
    -
    -
    -
    -
    -
    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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    And with loops

    - - - -
    -
    -
    -
    -
    -
    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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Using recursion

    - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    - -









    -

    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

    - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    - -









    -

    The syntax a.dot(b) when finding the dot product

    - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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: -

    - - - -
    -
    -
    -
    -
    -
    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).
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    - -

    The documentation recommends to avoid inplace operations such as

    - - -
    -
    -
    -
    -
    -
    a += b
    -a -= b
    -a*= b
    -a /=b
     
    diff --git a/doc/pub/week39/html/week39.html b/doc/pub/week39/html/week39.html index df5e22ed6..82bb8a138 100644 --- a/doc/pub/week39/html/week39.html +++ b/doc/pub/week39/html/week39.html @@ -282,46 +282,10 @@ div.toc p,a { 2, None, 'program-for-stochastic-gradient'), - ('Momentum based GD', 2, None, 'momentum-based-gd'), - ('More on momentum based approaches', + ('Code with a Number of Minibatches which varies', 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')]} + 'code-with-a-number-of-minibatches-which-varies')]} end of tocinfo --> @@ -2188,848 +2152,81 @@ plt.show()

    Challenge: try to write a similar code for a Logistic Regression case.











    -

    Momentum based GD

    +

    Code with a Number of Minibatches which varies

    -

    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 -

    +

    In the code here we vary the number of mini-batches.

    -$$ -\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} -$$ - -

    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} \).

    - -









    -

    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 -

    - -$$ -m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). -$$ - -

    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}). -$$ - -

    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. -$$ - - -









    -

    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: -

    - -$$ -\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. -$$ - -

    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 -

    - -$$ -\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} -$$ - -

    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 \).

    - -









    -

    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. -

    - -









    -

    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 -

    - -$$ -\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} -$$ - -

    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. -

    - -









    -

    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) -

    - -$$ -\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} -$$ - -

    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 = \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}. -$$ - - -









    -

    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.

    - -









    -

    Automatic differentiation

    - -

    Automatic differentiation (AD), -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 -

    -$$ -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 autograd we have

    - - - +
    -
    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))))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    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. -

    - - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    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. -

    - - - -
    -
    -
    -
    -
    -
    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) ))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    - -









    -

    More complicated functions using the elements of their arguments directly

    - - - -
    -
    -
    -
    -
    -
    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)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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. -

    - - -

    Functions using mathematical functions from Numpy

    - - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    More autograd

    - - - -
    -
    -
    -
    -
    -
    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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    And with loops

    - - - -
    -
    -
    -
    -
    -
    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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Using recursion

    - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    - -









    -

    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

    - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    - -









    -

    The syntax a.dot(b) when finding the dot product

    - - -
    -
    -
    -
    -
    -
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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: -

    - - - -
    -
    -
    -
    -
    -
    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).
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    - -

    The documentation recommends to avoid inplace operations such as

    - - -
    -
    -
    -
    -
    -
    a += b
    -a -= b
    -a*= b
    -a /=b
    +  
    # Importing various packages
    +from math import exp, sqrt
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +
    +for iter in range(Niterations):
    +    gradients = 2.0/n*X.T @ ((X @ theta)-y)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = np.random.randint(m)
    +        xi = X[random_index*M:random_index*M+M]
    +        yi = y[random_index*M:random_index*M+M]
    +        gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
     
    diff --git a/doc/pub/week39/ipynb/ipynb-week39-src.tar.gz b/doc/pub/week39/ipynb/ipynb-week39-src.tar.gz index 80ec2fb18..3e20937d1 100644 Binary files a/doc/pub/week39/ipynb/ipynb-week39-src.tar.gz and b/doc/pub/week39/ipynb/ipynb-week39-src.tar.gz differ diff --git a/doc/pub/week39/ipynb/week39.ipynb b/doc/pub/week39/ipynb/week39.ipynb index f6f0b3473..065b14e68 100644 --- a/doc/pub/week39/ipynb/week39.ipynb +++ b/doc/pub/week39/ipynb/week39.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "de52ab2c", + "id": "f128077b", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "852fb5f5", + "id": "88eb0662", "metadata": { "editable": true }, @@ -29,7 +29,7 @@ }, { "cell_type": "markdown", - "id": "8d300952", + "id": "ef4b2c9f", "metadata": { "editable": true }, @@ -55,7 +55,7 @@ }, { "cell_type": "markdown", - "id": "6d9c9efb", + "id": "ea15a627", "metadata": { "editable": true }, @@ -67,7 +67,7 @@ }, { "cell_type": "markdown", - "id": "0672e884", + "id": "8f497e37", "metadata": { "editable": true }, @@ -86,7 +86,7 @@ { "cell_type": "code", "execution_count": 1, - "id": "a91f4b13", + "id": "1f28007d", "metadata": { "collapsed": false, "editable": true @@ -143,7 +143,7 @@ }, { "cell_type": "markdown", - "id": "1cc7156d", + "id": "53dcc56a", "metadata": { "editable": true }, @@ -155,7 +155,7 @@ }, { "cell_type": "markdown", - "id": "f82c0e28", + "id": "1c24f55e", "metadata": { "editable": true }, @@ -170,7 +170,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "3e136826", + "id": "826e8ebc", "metadata": { "collapsed": false, "editable": true @@ -223,7 +223,7 @@ }, { "cell_type": "markdown", - "id": "12359ccb", + "id": "575ec2af", "metadata": { "editable": true }, @@ -238,7 +238,7 @@ }, { "cell_type": "markdown", - "id": "703cf65f", + "id": "f1d41e62", "metadata": { "editable": true }, @@ -258,7 +258,7 @@ { "cell_type": "code", "execution_count": 3, - "id": "5c2a058b", + "id": "0f87e8b0", "metadata": { "collapsed": false, "editable": true @@ -312,7 +312,7 @@ }, { "cell_type": "markdown", - "id": "dee30ccc", + "id": "1501c5b4", "metadata": { "editable": true }, @@ -331,7 +331,7 @@ }, { "cell_type": "markdown", - "id": "01530e9f", + "id": "5a2e32c5", "metadata": { "editable": true }, @@ -348,7 +348,7 @@ }, { "cell_type": "markdown", - "id": "183b9704", + "id": "e1a1d1e6", "metadata": { "editable": true }, @@ -363,7 +363,7 @@ }, { "cell_type": "markdown", - "id": "37018028", + "id": "5311a844", "metadata": { "editable": true }, @@ -373,7 +373,7 @@ }, { "cell_type": "markdown", - "id": "5b9161d9", + "id": "415a12aa", "metadata": { "editable": true }, @@ -389,7 +389,7 @@ }, { "cell_type": "markdown", - "id": "45a7fdb3", + "id": "e9cb4b5b", "metadata": { "editable": true }, @@ -401,7 +401,7 @@ }, { "cell_type": "markdown", - "id": "59318dc7", + "id": "cae474f3", "metadata": { "editable": true }, @@ -412,7 +412,7 @@ }, { "cell_type": "markdown", - "id": "2bb87427", + "id": "397a0e28", "metadata": { "editable": true }, @@ -424,7 +424,7 @@ }, { "cell_type": "markdown", - "id": "3801657e", + "id": "69de8cfd", "metadata": { "editable": true }, @@ -434,7 +434,7 @@ }, { "cell_type": "markdown", - "id": "602c1a6f", + "id": "d29ad122", "metadata": { "editable": true }, @@ -448,7 +448,7 @@ }, { "cell_type": "markdown", - "id": "bf3ab8e7", + "id": "60ffe26f", "metadata": { "editable": true }, @@ -460,7 +460,7 @@ }, { "cell_type": "markdown", - "id": "a183e3d5", + "id": "4a46900d", "metadata": { "editable": true }, @@ -470,7 +470,7 @@ }, { "cell_type": "markdown", - "id": "08d7eebc", + "id": "2d334287", "metadata": { "editable": true }, @@ -482,7 +482,7 @@ }, { "cell_type": "markdown", - "id": "7834a0d8", + "id": "07bbf1c5", "metadata": { "editable": true }, @@ -494,7 +494,7 @@ }, { "cell_type": "markdown", - "id": "0e4f6694", + "id": "0f6955e9", "metadata": { "editable": true }, @@ -514,7 +514,7 @@ }, { "cell_type": "markdown", - "id": "bd784119", + "id": "016a3ed1", "metadata": { "editable": true }, @@ -530,7 +530,7 @@ }, { "cell_type": "markdown", - "id": "1c971d1b", + "id": "e687408a", "metadata": { "editable": true }, @@ -546,7 +546,7 @@ }, { "cell_type": "markdown", - "id": "35a4d166", + "id": "8153a1ef", "metadata": { "editable": true }, @@ -557,7 +557,7 @@ }, { "cell_type": "markdown", - "id": "a80ede20", + "id": "8a6508af", "metadata": { "editable": true }, @@ -569,7 +569,7 @@ }, { "cell_type": "markdown", - "id": "318a0a08", + "id": "81ecbeb8", "metadata": { "editable": true }, @@ -579,7 +579,7 @@ }, { "cell_type": "markdown", - "id": "79b0ae38", + "id": "73ffd285", "metadata": { "editable": true }, @@ -591,7 +591,7 @@ }, { "cell_type": "markdown", - "id": "b17a388e", + "id": "e3230763", "metadata": { "editable": true }, @@ -601,7 +601,7 @@ }, { "cell_type": "markdown", - "id": "66a91a56", + "id": "fcd1e9f5", "metadata": { "editable": true }, @@ -613,7 +613,7 @@ }, { "cell_type": "markdown", - "id": "78f3baac", + "id": "c162cd0f", "metadata": { "editable": true }, @@ -635,7 +635,7 @@ }, { "cell_type": "markdown", - "id": "39ad1e8c", + "id": "ae042626", "metadata": { "editable": true }, @@ -648,7 +648,7 @@ }, { "cell_type": "markdown", - "id": "84da41c2", + "id": "c15dcfe7", "metadata": { "editable": true }, @@ -661,7 +661,7 @@ }, { "cell_type": "markdown", - "id": "7d9d28c2", + "id": "f441f82b", "metadata": { "editable": true }, @@ -671,7 +671,7 @@ }, { "cell_type": "markdown", - "id": "2396d542", + "id": "0bcf9fbb", "metadata": { "editable": true }, @@ -689,7 +689,7 @@ }, { "cell_type": "markdown", - "id": "a674eefc", + "id": "a5ce05a3", "metadata": { "editable": true }, @@ -699,7 +699,7 @@ }, { "cell_type": "markdown", - "id": "512e74e4", + "id": "537bd35d", "metadata": { "editable": true }, @@ -714,7 +714,7 @@ }, { "cell_type": "markdown", - "id": "3f9b1466", + "id": "c1ea25fd", "metadata": { "editable": true }, @@ -724,7 +724,7 @@ }, { "cell_type": "markdown", - "id": "f59aca60", + "id": "f86025d3", "metadata": { "editable": true }, @@ -738,7 +738,7 @@ }, { "cell_type": "markdown", - "id": "2fa2166e", + "id": "6eab3c0f", "metadata": { "editable": true }, @@ -748,7 +748,7 @@ }, { "cell_type": "markdown", - "id": "fb17ebb4", + "id": "64eb342e", "metadata": { "editable": true }, @@ -762,7 +762,7 @@ }, { "cell_type": "markdown", - "id": "d3d92dc1", + "id": "74504c64", "metadata": { "editable": true }, @@ -777,7 +777,7 @@ }, { "cell_type": "markdown", - "id": "00e0ec40", + "id": "888900dc", "metadata": { "editable": true }, @@ -794,7 +794,7 @@ }, { "cell_type": "markdown", - "id": "3c8b259c", + "id": "9ef0d6b7", "metadata": { "editable": true }, @@ -806,7 +806,7 @@ }, { "cell_type": "markdown", - "id": "2ac24c8e", + "id": "711f9890", "metadata": { "editable": true }, @@ -820,7 +820,7 @@ }, { "cell_type": "markdown", - "id": "5324c99e", + "id": "5f512c94", "metadata": { "editable": true }, @@ -835,7 +835,7 @@ }, { "cell_type": "markdown", - "id": "dc1a2974", + "id": "20ebe957", "metadata": { "editable": true }, @@ -847,7 +847,7 @@ }, { "cell_type": "markdown", - "id": "24016f18", + "id": "24bfec40", "metadata": { "editable": true }, @@ -858,7 +858,7 @@ }, { "cell_type": "markdown", - "id": "7da1de9c", + "id": "afa92ed3", "metadata": { "editable": true }, @@ -886,7 +886,7 @@ }, { "cell_type": "markdown", - "id": "76de1f0e", + "id": "be78c7ff", "metadata": { "editable": true }, @@ -908,7 +908,7 @@ }, { "cell_type": "markdown", - "id": "ce4f8111", + "id": "b48631d0", "metadata": { "editable": true }, @@ -930,7 +930,7 @@ }, { "cell_type": "markdown", - "id": "b54884b5", + "id": "74f9b42d", "metadata": { "editable": true }, @@ -942,7 +942,7 @@ }, { "cell_type": "markdown", - "id": "847b775c", + "id": "1f3c24ad", "metadata": { "editable": true }, @@ -979,7 +979,7 @@ }, { "cell_type": "markdown", - "id": "605e6362", + "id": "cef1cbcf", "metadata": { "editable": true }, @@ -1007,7 +1007,7 @@ }, { "cell_type": "markdown", - "id": "c560914a", + "id": "b48fc102", "metadata": { "editable": true }, @@ -1037,7 +1037,7 @@ }, { "cell_type": "markdown", - "id": "d17ecb27", + "id": "8771707f", "metadata": { "editable": true }, @@ -1057,7 +1057,7 @@ }, { "cell_type": "markdown", - "id": "1ab9d4f4", + "id": "e3699e3c", "metadata": { "editable": true }, @@ -1069,7 +1069,7 @@ }, { "cell_type": "markdown", - "id": "c9a33048", + "id": "3fe85e9b", "metadata": { "editable": true }, @@ -1079,7 +1079,7 @@ }, { "cell_type": "markdown", - "id": "12e64923", + "id": "2d274e5f", "metadata": { "editable": true }, @@ -1091,7 +1091,7 @@ }, { "cell_type": "markdown", - "id": "ab685f44", + "id": "1d8977ca", "metadata": { "editable": true }, @@ -1103,7 +1103,7 @@ }, { "cell_type": "markdown", - "id": "5408f0b0", + "id": "1a731287", "metadata": { "editable": true }, @@ -1115,7 +1115,7 @@ }, { "cell_type": "markdown", - "id": "948770b2", + "id": "4e1a0f0f", "metadata": { "editable": true }, @@ -1127,7 +1127,7 @@ }, { "cell_type": "markdown", - "id": "30214ae8", + "id": "e3cbbeae", "metadata": { "editable": true }, @@ -1138,7 +1138,7 @@ }, { "cell_type": "markdown", - "id": "61c1136e", + "id": "76da825c", "metadata": { "editable": true }, @@ -1151,7 +1151,7 @@ }, { "cell_type": "markdown", - "id": "f2294a2e", + "id": "5ca66074", "metadata": { "editable": true }, @@ -1163,7 +1163,7 @@ }, { "cell_type": "markdown", - "id": "3fb5eafd", + "id": "e656b7c1", "metadata": { "editable": true }, @@ -1173,7 +1173,7 @@ }, { "cell_type": "markdown", - "id": "a3d8069f", + "id": "95dc0049", "metadata": { "editable": true }, @@ -1185,7 +1185,7 @@ }, { "cell_type": "markdown", - "id": "b988ee43", + "id": "651ce9ba", "metadata": { "editable": true }, @@ -1195,7 +1195,7 @@ }, { "cell_type": "markdown", - "id": "15d398b5", + "id": "a0363bec", "metadata": { "editable": true }, @@ -1206,7 +1206,7 @@ }, { "cell_type": "markdown", - "id": "70530c03", + "id": "c8baf68f", "metadata": { "editable": true }, @@ -1218,7 +1218,7 @@ }, { "cell_type": "markdown", - "id": "afe7053f", + "id": "d6e62d6a", "metadata": { "editable": true }, @@ -1230,7 +1230,7 @@ }, { "cell_type": "markdown", - "id": "3ca18c80", + "id": "fa534fd5", "metadata": { "editable": true }, @@ -1242,7 +1242,7 @@ }, { "cell_type": "markdown", - "id": "65fc37b0", + "id": "15b4dd39", "metadata": { "editable": true }, @@ -1253,7 +1253,7 @@ }, { "cell_type": "markdown", - "id": "105051de", + "id": "386838de", "metadata": { "editable": true }, @@ -1264,7 +1264,7 @@ }, { "cell_type": "markdown", - "id": "1df9ace3", + "id": "8fa736a3", "metadata": { "editable": true }, @@ -1276,7 +1276,7 @@ }, { "cell_type": "markdown", - "id": "aa3a4868", + "id": "3bce4699", "metadata": { "editable": true }, @@ -1286,7 +1286,7 @@ }, { "cell_type": "markdown", - "id": "abd24903", + "id": "d4e0deed", "metadata": { "editable": true }, @@ -1298,7 +1298,7 @@ }, { "cell_type": "markdown", - "id": "e02e437b", + "id": "5fedaaee", "metadata": { "editable": true }, @@ -1308,7 +1308,7 @@ }, { "cell_type": "markdown", - "id": "a4e930d4", + "id": "52744cc4", "metadata": { "editable": true }, @@ -1320,7 +1320,7 @@ }, { "cell_type": "markdown", - "id": "e77f1392", + "id": "fafbca27", "metadata": { "editable": true }, @@ -1330,7 +1330,7 @@ }, { "cell_type": "markdown", - "id": "1c386f65", + "id": "46646d49", "metadata": { "editable": true }, @@ -1342,7 +1342,7 @@ }, { "cell_type": "markdown", - "id": "dbea410e", + "id": "f0380d98", "metadata": { "editable": true }, @@ -1352,7 +1352,7 @@ }, { "cell_type": "markdown", - "id": "b8ebcdca", + "id": "341fabc0", "metadata": { "editable": true }, @@ -1364,7 +1364,7 @@ }, { "cell_type": "markdown", - "id": "cdde0e61", + "id": "2ccbee55", "metadata": { "editable": true }, @@ -1375,7 +1375,7 @@ { "cell_type": "code", "execution_count": 4, - "id": "ffef5ad1", + "id": "e9cd098d", "metadata": { "collapsed": false, "editable": true @@ -1406,7 +1406,7 @@ }, { "cell_type": "markdown", - "id": "d4134df3", + "id": "d3d87f50", "metadata": { "editable": true }, @@ -1417,7 +1417,7 @@ { "cell_type": "code", "execution_count": 5, - "id": "59acf7b7", + "id": "6573ed86", "metadata": { "collapsed": false, "editable": true @@ -1431,7 +1431,7 @@ }, { "cell_type": "markdown", - "id": "3f7a4a83", + "id": "37a19a96", "metadata": { "editable": true }, @@ -1442,7 +1442,7 @@ { "cell_type": "code", "execution_count": 6, - "id": "1fcf7778", + "id": "cfa939b3", "metadata": { "collapsed": false, "editable": true @@ -1455,7 +1455,7 @@ }, { "cell_type": "markdown", - "id": "800a0d42", + "id": "5e8a1468", "metadata": { "editable": true }, @@ -1466,7 +1466,7 @@ { "cell_type": "code", "execution_count": 7, - "id": "364116b1", + "id": "ddd136f1", "metadata": { "collapsed": false, "editable": true @@ -1484,7 +1484,7 @@ }, { "cell_type": "markdown", - "id": "3ab19813", + "id": "1db3d7c1", "metadata": { "editable": true }, @@ -1495,7 +1495,7 @@ { "cell_type": "code", "execution_count": 8, - "id": "d56b2826", + "id": "b100941f", "metadata": { "collapsed": false, "editable": true @@ -1510,7 +1510,7 @@ }, { "cell_type": "markdown", - "id": "a4226299", + "id": "e93f8506", "metadata": { "editable": true }, @@ -1520,7 +1520,7 @@ }, { "cell_type": "markdown", - "id": "e9cd109f", + "id": "c554b744", "metadata": { "editable": true }, @@ -1534,7 +1534,7 @@ }, { "cell_type": "markdown", - "id": "ca85844f", + "id": "870f34c0", "metadata": { "editable": true }, @@ -1546,7 +1546,7 @@ }, { "cell_type": "markdown", - "id": "3595e062", + "id": "6ccf178c", "metadata": { "editable": true }, @@ -1557,7 +1557,7 @@ }, { "cell_type": "markdown", - "id": "73777697", + "id": "fc33ba76", "metadata": { "editable": true }, @@ -1569,7 +1569,7 @@ }, { "cell_type": "markdown", - "id": "fe726ca0", + "id": "aca5ae3f", "metadata": { "editable": true }, @@ -1580,7 +1580,7 @@ }, { "cell_type": "markdown", - "id": "48f71bad", + "id": "2acb10e1", "metadata": { "editable": true }, @@ -1591,7 +1591,7 @@ }, { "cell_type": "markdown", - "id": "737aa806", + "id": "a84cb95d", "metadata": { "editable": true }, @@ -1603,7 +1603,7 @@ }, { "cell_type": "markdown", - "id": "6670ac7c", + "id": "7e0d9442", "metadata": { "editable": true }, @@ -1613,7 +1613,7 @@ }, { "cell_type": "markdown", - "id": "27d92a3f", + "id": "970ab4ca", "metadata": { "editable": true }, @@ -1625,7 +1625,7 @@ }, { "cell_type": "markdown", - "id": "ae9a5d96", + "id": "479963af", "metadata": { "editable": true }, @@ -1637,7 +1637,7 @@ }, { "cell_type": "markdown", - "id": "9aa022a3", + "id": "044c0e28", "metadata": { "editable": true }, @@ -1649,7 +1649,7 @@ }, { "cell_type": "markdown", - "id": "a5283643", + "id": "7220bbac", "metadata": { "editable": true }, @@ -1661,7 +1661,7 @@ }, { "cell_type": "markdown", - "id": "841a2814", + "id": "55e083e5", "metadata": { "editable": true }, @@ -1672,7 +1672,7 @@ }, { "cell_type": "markdown", - "id": "712dd44f", + "id": "ef3b47b4", "metadata": { "editable": true }, @@ -1684,7 +1684,7 @@ }, { "cell_type": "markdown", - "id": "a8b8e47a", + "id": "a55e5078", "metadata": { "editable": true }, @@ -1694,7 +1694,7 @@ }, { "cell_type": "markdown", - "id": "bb0d022b", + "id": "f0d7c81e", "metadata": { "editable": true }, @@ -1706,7 +1706,7 @@ }, { "cell_type": "markdown", - "id": "2dd6b830", + "id": "842b4bc7", "metadata": { "editable": true }, @@ -1716,7 +1716,7 @@ }, { "cell_type": "markdown", - "id": "4d2e50c5", + "id": "e7404a0b", "metadata": { "editable": true }, @@ -1728,7 +1728,7 @@ }, { "cell_type": "markdown", - "id": "bffb4d24", + "id": "9f324fff", "metadata": { "editable": true }, @@ -1748,7 +1748,7 @@ }, { "cell_type": "markdown", - "id": "eb0a90ef", + "id": "a5a3b5f2", "metadata": { "editable": true }, @@ -1760,7 +1760,7 @@ }, { "cell_type": "markdown", - "id": "f1933be9", + "id": "ae6a0963", "metadata": { "editable": true }, @@ -1770,7 +1770,7 @@ }, { "cell_type": "markdown", - "id": "c485dce6", + "id": "3af5e327", "metadata": { "editable": true }, @@ -1782,7 +1782,7 @@ }, { "cell_type": "markdown", - "id": "0b047b67", + "id": "ac7efa8a", "metadata": { "editable": true }, @@ -1792,7 +1792,7 @@ }, { "cell_type": "markdown", - "id": "90a18fe4", + "id": "ce82cbc2", "metadata": { "editable": true }, @@ -1803,7 +1803,7 @@ }, { "cell_type": "markdown", - "id": "7403961b", + "id": "16407f07", "metadata": { "editable": true }, @@ -1815,7 +1815,7 @@ }, { "cell_type": "markdown", - "id": "45a4ed5a", + "id": "54748ace", "metadata": { "editable": true }, @@ -1827,7 +1827,7 @@ }, { "cell_type": "markdown", - "id": "43117fb3", + "id": "bd74fc63", "metadata": { "editable": true }, @@ -1839,7 +1839,7 @@ }, { "cell_type": "markdown", - "id": "9b86e550", + "id": "49569159", "metadata": { "editable": true }, @@ -1852,7 +1852,7 @@ }, { "cell_type": "markdown", - "id": "1e73a8a4", + "id": "d2abfb46", "metadata": { "editable": true }, @@ -1863,7 +1863,7 @@ }, { "cell_type": "markdown", - "id": "4f079500", + "id": "16b2345b", "metadata": { "editable": true }, @@ -1875,7 +1875,7 @@ }, { "cell_type": "markdown", - "id": "a77b9760", + "id": "bc54c087", "metadata": { "editable": true }, @@ -1891,7 +1891,7 @@ }, { "cell_type": "markdown", - "id": "b8ff988f", + "id": "f00a154f", "metadata": { "editable": true }, @@ -1903,7 +1903,7 @@ }, { "cell_type": "markdown", - "id": "5d200121", + "id": "6aaa442f", "metadata": { "editable": true }, @@ -1914,7 +1914,7 @@ }, { "cell_type": "markdown", - "id": "5a0be40f", + "id": "f972539b", "metadata": { "editable": true }, @@ -1926,7 +1926,7 @@ }, { "cell_type": "markdown", - "id": "d2b03e84", + "id": "2c4f7954", "metadata": { "editable": true }, @@ -1936,7 +1936,7 @@ }, { "cell_type": "markdown", - "id": "26767458", + "id": "7b06e435", "metadata": { "editable": true }, @@ -1948,7 +1948,7 @@ }, { "cell_type": "markdown", - "id": "19a09298", + "id": "0175754d", "metadata": { "editable": true }, @@ -1958,7 +1958,7 @@ }, { "cell_type": "markdown", - "id": "358fcc5f", + "id": "882eba77", "metadata": { "editable": true }, @@ -1970,7 +1970,7 @@ }, { "cell_type": "markdown", - "id": "211e3885", + "id": "8d70feb9", "metadata": { "editable": true }, @@ -1980,7 +1980,7 @@ }, { "cell_type": "markdown", - "id": "a3d918c2", + "id": "f14319c2", "metadata": { "editable": true }, @@ -1992,7 +1992,7 @@ }, { "cell_type": "markdown", - "id": "1a8646c6", + "id": "8ea48edc", "metadata": { "editable": true }, @@ -2016,7 +2016,7 @@ { "cell_type": "code", "execution_count": 9, - "id": "2a58fc5f", + "id": "c58d7c63", "metadata": { "collapsed": false, "editable": true @@ -2029,7 +2029,7 @@ }, { "cell_type": "markdown", - "id": "f22f4c05", + "id": "55926838", "metadata": { "editable": true }, @@ -2040,7 +2040,7 @@ }, { "cell_type": "markdown", - "id": "b359c45e", + "id": "87cc7056", "metadata": { "editable": true }, @@ -2052,7 +2052,7 @@ }, { "cell_type": "markdown", - "id": "26f78997", + "id": "2b937506", "metadata": { "editable": true }, @@ -2062,7 +2062,7 @@ }, { "cell_type": "markdown", - "id": "fc72c351", + "id": "82cca67c", "metadata": { "editable": true }, @@ -2074,7 +2074,7 @@ }, { "cell_type": "markdown", - "id": "a22fd803", + "id": "fbd011b6", "metadata": { "editable": true }, @@ -2088,7 +2088,7 @@ }, { "cell_type": "markdown", - "id": "a1c24abc", + "id": "4b127773", "metadata": { "editable": true }, @@ -2104,7 +2104,7 @@ }, { "cell_type": "markdown", - "id": "879e4d0b", + "id": "3711a429", "metadata": { "editable": true }, @@ -2114,7 +2114,7 @@ }, { "cell_type": "markdown", - "id": "cad58ece", + "id": "10e974fa", "metadata": { "editable": true }, @@ -2126,7 +2126,7 @@ }, { "cell_type": "markdown", - "id": "3ea805f2", + "id": "2c06dbe3", "metadata": { "editable": true }, @@ -2136,7 +2136,7 @@ }, { "cell_type": "markdown", - "id": "192e4a07", + "id": "f6e126f8", "metadata": { "editable": true }, @@ -2148,7 +2148,7 @@ }, { "cell_type": "markdown", - "id": "2ee9f4f7", + "id": "310ba565", "metadata": { "editable": true }, @@ -2162,7 +2162,7 @@ }, { "cell_type": "markdown", - "id": "ec667eee", + "id": "dac2f970", "metadata": { "editable": true }, @@ -2172,7 +2172,7 @@ }, { "cell_type": "markdown", - "id": "93286445", + "id": "3f7b08cc", "metadata": { "editable": true }, @@ -2183,7 +2183,7 @@ }, { "cell_type": "markdown", - "id": "c26f841a", + "id": "7f1f75ca", "metadata": { "editable": true }, @@ -2198,7 +2198,7 @@ }, { "cell_type": "markdown", - "id": "2adae630", + "id": "55f72e73", "metadata": { "editable": true }, @@ -2208,7 +2208,7 @@ }, { "cell_type": "markdown", - "id": "127611ba", + "id": "0b5caf9b", "metadata": { "editable": true }, @@ -2220,7 +2220,7 @@ }, { "cell_type": "markdown", - "id": "57db84ee", + "id": "3d3d1cd5", "metadata": { "editable": true }, @@ -2232,7 +2232,7 @@ }, { "cell_type": "markdown", - "id": "ab0d0e73", + "id": "7452f292", "metadata": { "editable": true }, @@ -2247,7 +2247,7 @@ }, { "cell_type": "markdown", - "id": "9ae554c4", + "id": "eece1578", "metadata": { "editable": true }, @@ -2260,7 +2260,7 @@ { "cell_type": "code", "execution_count": 10, - "id": "607de431", + "id": "633a72fc", "metadata": { "collapsed": false, "editable": true @@ -2317,7 +2317,7 @@ }, { "cell_type": "markdown", - "id": "87f5cbc4", + "id": "739723cf", "metadata": { "editable": true }, @@ -2328,7 +2328,7 @@ { "cell_type": "code", "execution_count": 11, - "id": "62f132db", + "id": "b2cf86e4", "metadata": { "collapsed": false, "editable": true @@ -2355,7 +2355,7 @@ }, { "cell_type": "markdown", - "id": "1ace856e", + "id": "7dfe7ad8", "metadata": { "editable": true }, @@ -2367,7 +2367,7 @@ }, { "cell_type": "markdown", - "id": "0215f5b5", + "id": "399c009b", "metadata": { "editable": true }, @@ -2379,7 +2379,7 @@ }, { "cell_type": "markdown", - "id": "791f46e6", + "id": "4428c518", "metadata": { "editable": true }, @@ -2389,7 +2389,7 @@ }, { "cell_type": "markdown", - "id": "3b02080c", + "id": "afeb211e", "metadata": { "editable": true }, @@ -2403,7 +2403,7 @@ }, { "cell_type": "markdown", - "id": "db7e17e4", + "id": "bbdf1e15", "metadata": { "editable": true }, @@ -2413,7 +2413,7 @@ }, { "cell_type": "markdown", - "id": "2fdde7e6", + "id": "9faab24a", "metadata": { "editable": true }, @@ -2425,7 +2425,7 @@ }, { "cell_type": "markdown", - "id": "2217e27b", + "id": "69d24d60", "metadata": { "editable": true }, @@ -2436,7 +2436,7 @@ }, { "cell_type": "markdown", - "id": "f3b99751", + "id": "13e793f1", "metadata": { "editable": true }, @@ -2451,7 +2451,7 @@ }, { "cell_type": "markdown", - "id": "82042b92", + "id": "e6427bfc", "metadata": { "editable": true }, @@ -2465,7 +2465,7 @@ }, { "cell_type": "markdown", - "id": "8ad6f60d", + "id": "2cf35c54", "metadata": { "editable": true }, @@ -2476,7 +2476,7 @@ { "cell_type": "code", "execution_count": 12, - "id": "2ba44646", + "id": "59efb4ab", "metadata": { "collapsed": false, "editable": true @@ -2537,7 +2537,7 @@ }, { "cell_type": "markdown", - "id": "39f26c17", + "id": "c6dcc84a", "metadata": { "editable": true }, @@ -2559,7 +2559,7 @@ }, { "cell_type": "markdown", - "id": "1b7b916c", + "id": "c4eb06f1", "metadata": { "editable": true }, @@ -2571,7 +2571,7 @@ }, { "cell_type": "markdown", - "id": "926acd76", + "id": "1c79c027", "metadata": { "editable": true }, @@ -2581,7 +2581,7 @@ }, { "cell_type": "markdown", - "id": "2225fdb2", + "id": "de4176bc", "metadata": { "editable": true }, @@ -2598,7 +2598,7 @@ }, { "cell_type": "markdown", - "id": "b527275d", + "id": "6ae32c9d", "metadata": { "editable": true }, @@ -2611,7 +2611,7 @@ }, { "cell_type": "markdown", - "id": "54215210", + "id": "4897da29", "metadata": { "editable": true }, @@ -2624,7 +2624,7 @@ }, { "cell_type": "markdown", - "id": "faf3e2ae", + "id": "9fbdb5d3", "metadata": { "editable": true }, @@ -2637,7 +2637,7 @@ }, { "cell_type": "markdown", - "id": "e80cc712", + "id": "3c2d61cb", "metadata": { "editable": true }, @@ -2651,7 +2651,7 @@ }, { "cell_type": "markdown", - "id": "c8f41f8a", + "id": "89bee80f", "metadata": { "editable": true }, @@ -2673,7 +2673,7 @@ }, { "cell_type": "markdown", - "id": "bc64a1b3", + "id": "5a5d1781", "metadata": { "editable": true }, @@ -2688,7 +2688,7 @@ }, { "cell_type": "markdown", - "id": "370619e3", + "id": "fa2f5d32", "metadata": { "editable": true }, @@ -2700,7 +2700,7 @@ }, { "cell_type": "markdown", - "id": "39f84e51", + "id": "682c24e0", "metadata": { "editable": true }, @@ -2713,7 +2713,7 @@ }, { "cell_type": "markdown", - "id": "8badbdbb", + "id": "9d1616d5", "metadata": { "editable": true }, @@ -2727,7 +2727,7 @@ }, { "cell_type": "markdown", - "id": "fb189ee6", + "id": "4727394c", "metadata": { "editable": true }, @@ -2738,7 +2738,7 @@ { "cell_type": "code", "execution_count": 13, - "id": "1b10dd63", + "id": "416e28d2", "metadata": { "collapsed": false, "editable": true @@ -2763,7 +2763,7 @@ }, { "cell_type": "markdown", - "id": "60c85a6a", + "id": "aab85c9b", "metadata": { "editable": true }, @@ -2779,7 +2779,7 @@ }, { "cell_type": "markdown", - "id": "03056842", + "id": "deccca01", "metadata": { "editable": true }, @@ -2800,7 +2800,7 @@ }, { "cell_type": "markdown", - "id": "d0fc69b6", + "id": "f29f65b8", "metadata": { "editable": true }, @@ -2823,7 +2823,7 @@ { "cell_type": "code", "execution_count": 14, - "id": "477f8067", + "id": "92349988", "metadata": { "collapsed": false, "editable": true @@ -2858,7 +2858,7 @@ }, { "cell_type": "markdown", - "id": "b2df0f6e", + "id": "fd9af7b6", "metadata": { "editable": true }, @@ -2869,7 +2869,7 @@ { "cell_type": "code", "execution_count": 15, - "id": "e6e21347", + "id": "2ffb14c6", "metadata": { "collapsed": false, "editable": true @@ -2945,7 +2945,7 @@ }, { "cell_type": "markdown", - "id": "74cb0f5b", + "id": "9f39fc35", "metadata": { "editable": true }, @@ -2955,1177 +2955,91 @@ }, { "cell_type": "markdown", - "id": "263a062f", + "id": "bd845e63", "metadata": { "editable": true }, "source": [ - "## Momentum based GD\n", + "## Code with a Number of Minibatches which varies\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", - "id": "5acea3b6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "86b6ce74", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
    \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", - "id": "6ba3933e", - "metadata": { - "editable": true - }, - "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", - "id": "a6f7b01b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "66265044", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." - ] - }, - { - "cell_type": "markdown", - "id": "c0c27f64", - "metadata": { - "editable": true - }, - "source": [ - "## 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", - "id": "b56e7234", - "metadata": { - "editable": true - }, - "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", - "id": "ea8ea658", - "metadata": { - "editable": true - }, - "source": [ - "We can discretize this equation in the usual way to get" - ] - }, - { - "cell_type": "markdown", - "id": "e4f1b7ba", - "metadata": { - "editable": true - }, - "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", - "id": "3dca8de6", - "metadata": { - "editable": true - }, - "source": [ - "Rearranging this equation, we can rewrite this as" - ] - }, - { - "cell_type": "markdown", - "id": "b4eed9ca", - "metadata": { - "editable": true - }, - "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", - "id": "1d004801", - "metadata": { - "editable": true - }, - "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", - "id": "ebad5b4c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "78e2425d", - "metadata": { - "editable": true - }, - "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", - "id": "d7528c9c", - "metadata": { - "editable": true - }, - "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", - "id": "92f6d9ee", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
    \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", - "id": "b3a14edc", - "metadata": { - "editable": true - }, - "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$." - ] - }, - { - "cell_type": "markdown", - "id": "1b49bdef", - "metadata": { - "editable": true - }, - "source": [ - "## Second moment of the gradient\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." - ] - }, - { - "cell_type": "markdown", - "id": "602dd2c7", - "metadata": { - "editable": true - }, - "source": [ - "## 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", - "id": "2da5dfb7", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
    \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", - "id": "ebf4a63b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "78f4edbe", - "metadata": { - "editable": true - }, - "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", - "id": "bdc9f8d2", - "metadata": { - "editable": true - }, - "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." - ] - }, - { - "cell_type": "markdown", - "id": "00095259", - "metadata": { - "editable": true - }, - "source": [ - "## 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", - "id": "4611ffb2", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
    \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", - "id": "096b4a4c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fcb52b2e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6997acaf", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d4f09801", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "49d19dec", - "metadata": { - "editable": true - }, - "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", - "id": "0d72a20c", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
    \n", - "\n", - "$$\n", - "\\begin{equation} \n", - "\\label{_auto5} \\tag{6}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1e7dd68d", - "metadata": { - "editable": true - }, - "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", - "id": "f44bae92", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta \\theta_{t+1}= -\\eta_t { \\boldsymbol{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c101ad6a", - "metadata": { - "editable": true - }, - "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." - ] - }, - { - "cell_type": "markdown", - "id": "2d4a7bad", - "metadata": { - "editable": true - }, - "source": [ - "## 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", - "Python has tools for so-called **automatic differentiation**.\n", - "Consider the following example" - ] - }, - { - "cell_type": "markdown", - "id": "1debafa2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2df83f23", - "metadata": { - "editable": true - }, - "source": [ - "which has the following derivative" - ] - }, - { - "cell_type": "markdown", - "id": "cbdc7d40", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f'(x) = \\cos\\left(2\\pi x + x^2\\right)\\left(2\\pi + 2x\\right)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "90c43fe1", - "metadata": { - "editable": true - }, - "source": [ - "Using **autograd** we have" + "In the code here we vary the number of mini-batches." ] }, { "cell_type": "code", "execution_count": 16, - "id": "d3f3c169", + "id": "b8c2c078", "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", - "id": "aaeb2f07", - "metadata": { - "editable": true - }, - "source": [ - "## 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": 17, - "id": "8b54b011", - "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", - "id": "a7d5c4a3", - "metadata": { - "editable": true - }, - "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": 18, - "id": "808d7257", - "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", - "id": "fcccacac", - "metadata": { - "editable": true - }, - "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." - ] - }, - { - "cell_type": "markdown", - "id": "07743bce", - "metadata": { - "editable": true - }, - "source": [ - "## More complicated functions using the elements of their arguments directly" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "462e5079", - "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", - "id": "f6f582e9", - "metadata": { - "editable": true - }, - "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." - ] - }, - { - "cell_type": "markdown", - "id": "fa8cd98d", - "metadata": { - "editable": true - }, - "source": [ - "## Functions using mathematical functions from Numpy" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "af9291a2", - "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", - "id": "c71170a0", - "metadata": { - "editable": true - }, - "source": [ - "## More autograd" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "70d22cd2", - "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", - "id": "49cff9c1", - "metadata": { - "editable": true - }, - "source": [ - "## And with loops" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "9bf07b91", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f6_for(x):\n", - " val = 0\n", - " for i in range(10):\n", - " val = val + x**i\n", - " return val\n", - "\n", - "def f6_while(x):\n", - " val = 0\n", - " i = 0\n", - " while i < 10:\n", - " val = val + x**i\n", - " i = i + 1\n", - " return val\n", - "\n", - "f6_for_grad = grad(f6_for)\n", - "f6_while_grad = grad(f6_while)\n", - "\n", - "x = 0.5\n", - "\n", - "# Print the computed derivaties of f6_for and f6_while\n", - "print(\"The computed derivative of f6_for at x = %g is: %g\"%(x,f6_for_grad(x)))\n", - "print(\"The computed derivative of f6_while at x = %g is: %g\"%(x,f6_while_grad(x)))" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "1433de4f", - "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", - "id": "739542d5", - "metadata": { - "editable": true - }, - "source": [ - "## Using recursion" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "71b47968", - "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", - "id": "90cd56de", - "metadata": { - "editable": true - }, - "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." - ] - }, - { - "cell_type": "markdown", - "id": "412f2188", - "metadata": { - "editable": true - }, - "source": [ - "## 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": 25, - "id": "9278db34", - "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", - "id": "b1c799c9", - "metadata": { - "editable": true - }, - "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." - ] - }, - { - "cell_type": "markdown", - "id": "9250081e", - "metadata": { - "editable": true - }, - "source": [ - "## The syntax a.dot(b) when finding the dot product" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "5f5ec5e4", - "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", - "id": "9b08f5cb", - "metadata": { - "editable": true - }, - "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": 27, - "id": "258048ca", - "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", - "id": "abebc622", - "metadata": { - "editable": true - }, - "source": [ - "## Recommended to avoid\n", - "The documentation recommends to avoid inplace operations such as" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "50463160", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "a += b\n", - "a -= b\n", - "a*= b\n", - "a /=b" + "# Importing various packages\n", + "from math import exp, sqrt\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = 2.0/n*X.T @ ((X @ theta)-y)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "for epoch in range(n_epochs):\n", + "# Can you figure out a better way of setting up the contributions to each batch?\n", + " for i in range(m):\n", + " random_index = np.random.randint(m)\n", + " xi = X[random_index*M:random_index*M+M]\n", + " yi = y[random_index*M:random_index*M+M]\n", + " gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" ] } ], diff --git a/doc/src/week39/week39.do.txt b/doc/src/week39/week39.do.txt index 5ccc0dfde..fb69cb5bb 100644 --- a/doc/src/week39/week39.do.txt +++ b/doc/src/week39/week39.do.txt @@ -1505,610 +1505,77 @@ _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() - +===== Code with a Number of Minibatches which varies ===== + +In the code here we vary the number of mini-batches. +!bc pycode +# Importing various packages +from math import exp, sqrt +from random import random, seed +import numpy as np +import matplotlib.pyplot as plt + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 + + +for iter in range(Niterations): + gradients = 2.0/n*X.T @ ((X @ theta)-y) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +t0, t1 = 5, 50 +def learning_schedule(t): + return t0/(t+t1) + +theta = np.random.randn(2,1) + +for epoch in range(n_epochs): +# Can you figure out a better way of setting up the contributions to each batch? + for i in range(m): + random_index = np.random.randint(m) + xi = X[random_index*M:random_index*M+M] + yi = y[random_index*M:random_index*M+M] + gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi) + eta = learning_schedule(epoch*m+i) + theta = theta - eta*gradients +print("theta from own sdg") +print(theta) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') 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 - - - -