From 878f01db99e7a485a861bf213d51fcc0e755e76e Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Mon, 26 Sep 2022 06:43:06 +0200 Subject: [PATCH] update week 39 --- doc/pub/week39/html/week39-bs.html | 229 +- doc/pub/week39/html/week39-reveal.html | 1773 ++++++++++-- doc/pub/week39/html/week39-solarized.html | 1798 +++++++++++-- doc/pub/week39/html/week39.html | 1798 +++++++++++-- doc/pub/week39/ipynb/ipynb-week39-src.tar.gz | Bin 191 -> 193 bytes doc/pub/week39/ipynb/week39.ipynb | 2544 ++++++++++++++---- doc/src/week39/week39.do.txt | 1291 +++++++-- 7 files changed, 7907 insertions(+), 1526 deletions(-) diff --git a/doc/pub/week39/html/week39-bs.html b/doc/pub/week39/html/week39-bs.html index 0756c0dbc..08bbbb758 100644 --- a/doc/pub/week39/html/week39-bs.html +++ b/doc/pub/week39/html/week39-bs.html @@ -38,12 +38,6 @@ doconce format html week39.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plan for week 39', 2, None, 'plan-for-week-39'), ('Thursday September 29', 2, None, 'thursday-september-29'), - ('Searching for Optimal Regularization Parameters $\\lambda$', - 2, - None, - 'searching-for-optimal-regularization-parameters-lambda'), - ('Grid Search', 2, None, 'grid-search'), - ('Randomized Grid Search', 2, None, 'randomized-grid-search'), ('Optimization, the central part of any Machine Learning ' 'algortithm', 2, @@ -159,8 +153,6 @@ doconce format html week39.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'using-gradient-descent-methods-limitations'), - ('Challenge yourself', 2, None, 'challenge-yourself'), - ('Friday September 30', 2, None, 'friday-september-30'), ('Stochastic Gradient Descent', 2, None, @@ -181,7 +173,80 @@ doconce format html week39.do.txt --html_style=bootstrap --pygments_html_style=d ('Code with a Number of Minibatches which varies', 2, None, - 'code-with-a-number-of-minibatches-which-varies')]} + 'code-with-a-number-of-minibatches-which-varies'), + ('Overview video on Stochastic Gradient Descent', + 2, + None, + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', + 2, + None, + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', + 2, + None, + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', + 2, + None, + 'slightly-different-approach'), + ('Program for stochastic gradient', + 2, + None, + 'program-for-stochastic-gradient'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', + 2, + None, + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', + 2, + None, + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('ADAM optimizer', 2, None, 'adam-optimizer'), + ('Practical tips', 2, None, 'practical-tips'), + ('Automatic differentiation', + 2, + None, + 'automatic-differentiation'), + ('Using autograd', 2, None, 'using-autograd'), + ('Autograd with more complicated functions', + 2, + None, + 'autograd-with-more-complicated-functions'), + ('More complicated functions using the elements of their ' + 'arguments directly', + 2, + None, + 'more-complicated-functions-using-the-elements-of-their-arguments-directly'), + ('Functions using mathematical functions from Numpy', + 2, + None, + 'functions-using-mathematical-functions-from-numpy'), + ('More autograd', 2, None, 'more-autograd'), + ('And with loops', 2, None, 'and-with-loops'), + ('Using recursion', 2, None, 'using-recursion'), + ('Unsupported functions', 2, None, 'unsupported-functions'), + ('The syntax a.dot(b) when finding the dot product', + 2, + None, + 'the-syntax-a-dot-b-when-finding-the-dot-product'), + ('Recommended to avoid', 2, None, 'recommended-to-avoid'), + ('Using Autograd with OLS', 2, None, 'using-autograd-with-ols'), + ('Including Stochastic Gradient Descent with Autograd', + 2, + None, + 'including-stochastic-gradient-descent-with-autograd'), + ('And Logistic Regression', 2, None, 'and-logistic-regression')]} end of tocinfo --> @@ -218,62 +283,90 @@ MathJax.Hub.Config({ @@ -299,11 +392,11 @@ MathJax.Hub.Config({ [1] Department of Physics, University of Oslo
-[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University

-

Aug 23, 2022

+

Sep 26, 2022


@@ -328,7 +421,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 59
  • +
  • 87
  • »
  • diff --git a/doc/pub/week39/html/week39-reveal.html b/doc/pub/week39/html/week39-reveal.html index a5ecf3ed0..dde9d35a3 100644 --- a/doc/pub/week39/html/week39-reveal.html +++ b/doc/pub/week39/html/week39-reveal.html @@ -180,11 +180,11 @@ MathJax.Hub.Config({ [1] Department of Physics, University of Oslo
    -[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University

    -

    Aug 23, 2022

    +

    Sep 26, 2022


    @@ -198,16 +198,18 @@ MathJax.Hub.Config({

    Plan for week 39

    See lecture notes for week 39. -For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well. +For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well.

    -For project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.55 and 5.7-5.11. +

    For Stochastic Gradient Descent, we recommend chapter 4 of Geron's text.

    + +For project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.5 and 5.7-5.11.

    These sections summarize neatly what we have done till now and point to what is coming with respect to deep learning.

    @@ -217,249 +219,6 @@ For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 Overview Video, why do we care about gradient methods? -
    -

    Searching for Optimal Regularization Parameters \( \lambda \)

    - -

    In project 1, when using Ridge and Lasso regression, we end up -searching for the optimal parameter \( \lambda \) which minimizes our -selected scores (MSE or \( R2 \) values for example). The brute force -approach, as discussed in the code here for Ridge regression, consists -in evaluating the MSE as function of different \( \lambda \) values. -Based on these calculations, one tries then to determine the value of the hyperparameter \( \lambda \) -which results in optimal scores (for example the smallest MSE or an \( R2=1 \)). -

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(2021)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -MSERidgePredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    RegRidge = linear_model.Ridge(lmb)
    -    RegRidge.fit(X_train,y_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Here we have performed a rather data greedy calculation as function of the regularization parameter \( \lambda \). There is no resampling here. The latter can easily be added by employing the function RidgeCV instead of just calling the Ridge function. For RidgeCV we need to pass the array of \( \lambda \) values. -By inspecting the figure we can in turn determine which is the optimal regularization parameter. -This becomes however less functional in the long run. -

    -
    - -
    - - -

    An alternative is to use the so-called grid search functionality -included with the library Scikit-Learn, as demonstrated for the same -example here. -

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import GridSearchCV
    -
    -def R2(y_data, y_model):
    -    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(2021)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -# Decide which values of lambda to use
    -nlambdas = 10
    -lambdas = np.logspace(-4, 2, nlambdas)
    -# create and fit a ridge regression model, testing each alpha
    -model = Ridge()
    -gridsearch = GridSearchCV(estimator=model, param_grid=dict(alpha=lambdas))
    -gridsearch.fit(X_train, y_train)
    -print(gridsearch)
    -ypredictRidge = gridsearch.predict(X_test)
    -# summarize the results of the grid search
    -print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}")
    -print(f"MSE score: {MSE(y_test,ypredictRidge)}")
    -print(f"R2 score: {R2(y_test,ypredictRidge)}")
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    By default the grid search function includes cross validation with -five folds. The Scikit-Learn -documentation -contains more information on how to set the different parameters. -

    - -

    If we take out the random noise, running the above codes results in \( \lambda=0 \) yielding the best fit.

    -
    - -
    - - -

    An alternative to the above manual grid set up, is to use a random -search where the parameters are tuned from a random distribution -(uniform below) for a fixed number of iterations. A model is -constructed and evaluated for each combination of chosen parameters. -We repeat the previous example but now with a random search. Note -that values of \( \lambda \) are now limited to be within \( x\in -[0,1] \). This domain may not be the most relevant one for the specific -case under study. -

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import GridSearchCV
    -from scipy.stats import uniform as randuniform
    -from sklearn.model_selection import RandomizedSearchCV
    -
    -
    -def R2(y_data, y_model):
    -    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(2021)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -param_grid = {'alpha': randuniform()}
    -# create and fit a ridge regression model, testing each alpha
    -model = Ridge()
    -gridsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)
    -gridsearch.fit(X_train, y_train)
    -print(gridsearch)
    -ypredictRidge = gridsearch.predict(X_test)
    -# summarize the results of the grid search
    -print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}")
    -print(f"MSE score: {MSE(y_test,ypredictRidge)}")
    -print(f"R2 score: {R2(y_test,ypredictRidge)}")
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Optimization, the central part of any Machine Learning algortithm

    @@ -1866,16 +1625,6 @@ plt.show()
    -
    -

    Challenge yourself

    - -

    Write a code which implements gradient descent for a logistic regression example.

    -
    - -
    -

    Friday September 30

    -
    -

    Stochastic Gradient Descent

    @@ -2277,6 +2026,1514 @@ plt.show()
    +
    +

    Overview video on Stochastic Gradient Descent

    + +What is Stochastic Gradient Descent +
    + +
    +

    Batches and mini-batches

    + +

    In gradient descent we compute the cost function and its gradient for all data points we have.

    + +

    In large-scale applications such as the ILSVRC challenge, the +training data can have on order of millions of examples. Hence, it +seems wasteful to compute the full cost function over the entire +training set in order to perform only a single parameter update. A +very common approach to addressing this challenge is to compute the +gradient over batches of the training data. For example, in current +a typical batch could contain some thousand examples from +an entire training set of several millions. This batch is then used to +perform a parameter update. +

    +
    + +
    +

    Stochastic Gradient Descent (SGD)

    + +

    In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set. +

    + +

    This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. +

    + +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    +
    + +
    +

    Stochastic Gradient Descent

    + +

    Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. +

    + +

    The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

    +

     
    +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ +

     
    +

    + +
    +

    Computation of gradients

    + +

    This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +

    +

     
    +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ +

     
    + +

    Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). +

    +
    + +
    +

    SGD example

    + +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). +

    + +

    The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +

    +

     
    +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ +

     
    +

    + +
    +

    The gradient step

    + +

    Thus a gradient descent step now looks like

    +

     
    +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ +

     
    + +

    where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. +

    +
    + +
    +

    Simple example code

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each mini-batche
    +m = int(n/M) #number of minibatches
    +n_epochs = 10 #number of epochs
    +
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for 
    +        j += 1
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. +

    +
    + +
    +

    When do we stop?

    + +

    A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. +

    +
    + +
    +

    Slightly different approach

    + +

    Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. +

    + +

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function

     
    +$$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ +

     
    goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    + +

    In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +def step_length(t,t0,t1):
    +    return t0/(t+t1)
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 500 #number of epochs
    +t0 = 1.0
    +t1 = 10
    +
    +gamma_j = t0/t1
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for beta
    +        t = epoch*m+i
    +        gamma_j = step_length(t,t0,t1)
    +        j += 1
    +
    +print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters \( t_0 \) and \( t_1 \).

    +
    + +
    +

    Program for stochastic gradient

    + + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +# 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 = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Replace or not

    + +

    In the above code, we have use replacement in setting up the +mini-batches. The discussion +here may be +useful. More material will be added later. +

    +
    + +
    +

    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 +

    + +

     
    +$$ +\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, Root Mean Squared Propagation (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
    +
    +# 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
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Using Autograd with OLS

    + +

    We conclude the part on optmization by showing how we can make codes +for linear regression and logistic regression using autograd. The +first example shows results with ordinary leats squares. +

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +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.pinv(XT_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
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    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)
    +
    +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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Including Stochastic Gradient Descent with Autograd

    +

    In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using autograd.

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +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.pinv(XT_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
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    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)
    +
    +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()
    +
    +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 = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    And Logistic Regression

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +from autograd import grad
    +
    +def sigmoid(x):
    +    return 0.5 * (np.tanh(x / 2.) + 1)
    +
    +def logistic_predictions(weights, inputs):
    +    # Outputs probability of a label being true according to logistic model.
    +    return sigmoid(np.dot(inputs, weights))
    +
    +def training_loss(weights):
    +    # Training loss is the negative log-likelihood of the training labels.
    +    preds = logistic_predictions(weights, inputs)
    +    label_probabilities = preds * targets + (1 - preds) * (1 - targets)
    +    return -np.sum(np.log(label_probabilities))
    +
    +# Build a toy dataset.
    +inputs = np.array([[0.52, 1.12,  0.77],
    +                   [0.88, -1.08, 0.15],
    +                   [0.52, 0.06, -1.30],
    +                   [0.74, -2.49, 1.39]])
    +targets = np.array([True, True, False, True])
    +
    +# Define a function that returns gradients of training loss using Autograd.
    +training_gradient_fun = grad(training_loss)
    +
    +# Optimize weights using gradient descent.
    +weights = np.array([0.0, 0.0, 0.0])
    +print("Initial loss:", training_loss(weights))
    +for i in range(100):
    +    weights -= training_gradient_fun(weights) * 0.01
    +
    +print("Trained loss:", training_loss(weights))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + diff --git a/doc/pub/week39/html/week39-solarized.html b/doc/pub/week39/html/week39-solarized.html index cf77c8573..a1b285df9 100644 --- a/doc/pub/week39/html/week39-solarized.html +++ b/doc/pub/week39/html/week39-solarized.html @@ -65,12 +65,6 @@ div.toc p,a { {'highest level': 2, 'sections': [('Plan for week 39', 2, None, 'plan-for-week-39'), ('Thursday September 29', 2, None, 'thursday-september-29'), - ('Searching for Optimal Regularization Parameters $\\lambda$', - 2, - None, - 'searching-for-optimal-regularization-parameters-lambda'), - ('Grid Search', 2, None, 'grid-search'), - ('Randomized Grid Search', 2, None, 'randomized-grid-search'), ('Optimization, the central part of any Machine Learning ' 'algortithm', 2, @@ -186,8 +180,6 @@ div.toc p,a { 2, None, 'using-gradient-descent-methods-limitations'), - ('Challenge yourself', 2, None, 'challenge-yourself'), - ('Friday September 30', 2, None, 'friday-september-30'), ('Stochastic Gradient Descent', 2, None, @@ -208,7 +200,80 @@ div.toc p,a { ('Code with a Number of Minibatches which varies', 2, None, - 'code-with-a-number-of-minibatches-which-varies')]} + 'code-with-a-number-of-minibatches-which-varies'), + ('Overview video on Stochastic Gradient Descent', + 2, + None, + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', + 2, + None, + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', + 2, + None, + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', + 2, + None, + 'slightly-different-approach'), + ('Program for stochastic gradient', + 2, + None, + 'program-for-stochastic-gradient'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', + 2, + None, + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', + 2, + None, + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('ADAM optimizer', 2, None, 'adam-optimizer'), + ('Practical tips', 2, None, 'practical-tips'), + ('Automatic differentiation', + 2, + None, + 'automatic-differentiation'), + ('Using autograd', 2, None, 'using-autograd'), + ('Autograd with more complicated functions', + 2, + None, + 'autograd-with-more-complicated-functions'), + ('More complicated functions using the elements of their ' + 'arguments directly', + 2, + None, + 'more-complicated-functions-using-the-elements-of-their-arguments-directly'), + ('Functions using mathematical functions from Numpy', + 2, + None, + 'functions-using-mathematical-functions-from-numpy'), + ('More autograd', 2, None, 'more-autograd'), + ('And with loops', 2, None, 'and-with-loops'), + ('Using recursion', 2, None, 'using-recursion'), + ('Unsupported functions', 2, None, 'unsupported-functions'), + ('The syntax a.dot(b) when finding the dot product', + 2, + None, + 'the-syntax-a-dot-b-when-finding-the-dot-product'), + ('Recommended to avoid', 2, None, 'recommended-to-avoid'), + ('Using Autograd with OLS', 2, None, 'using-autograd-with-ols'), + ('Including Stochastic Gradient Descent with Autograd', + 2, + None, + 'including-stochastic-gradient-descent-with-autograd'), + ('And Logistic Regression', 2, None, 'and-logistic-regression')]} end of tocinfo --> @@ -242,11 +307,11 @@ MathJax.Hub.Config({ [1] Department of Physics, University of Oslo
    -[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University

    -

    Aug 23, 2022

    +

    Sep 26, 2022


    @@ -254,15 +319,17 @@ MathJax.Hub.Config({

    Plan for week 39

    See lecture notes for week 39. -For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well. +For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well.

    -For project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.55 and 5.7-5.11. +

    For Stochastic Gradient Descent, we recommend chapter 4 of Geron's text.

    + +For project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.5 and 5.7-5.11.

    These sections summarize neatly what we have done till now and point to what is coming with respect to deep learning.











    @@ -270,247 +337,6 @@ For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 Overview Video, why do we care about gradient methods? -









    -

    Searching for Optimal Regularization Parameters \( \lambda \)

    - -

    In project 1, when using Ridge and Lasso regression, we end up -searching for the optimal parameter \( \lambda \) which minimizes our -selected scores (MSE or \( R2 \) values for example). The brute force -approach, as discussed in the code here for Ridge regression, consists -in evaluating the MSE as function of different \( \lambda \) values. -Based on these calculations, one tries then to determine the value of the hyperparameter \( \lambda \) -which results in optimal scores (for example the smallest MSE or an \( R2=1 \)). -

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(2021)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -MSERidgePredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    RegRidge = linear_model.Ridge(lmb)
    -    RegRidge.fit(X_train,y_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Here we have performed a rather data greedy calculation as function of the regularization parameter \( \lambda \). There is no resampling here. The latter can easily be added by employing the function RidgeCV instead of just calling the Ridge function. For RidgeCV we need to pass the array of \( \lambda \) values. -By inspecting the figure we can in turn determine which is the optimal regularization parameter. -This becomes however less functional in the long run. -

    - -









    - - -

    An alternative is to use the so-called grid search functionality -included with the library Scikit-Learn, as demonstrated for the same -example here. -

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import GridSearchCV
    -
    -def R2(y_data, y_model):
    -    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(2021)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -# Decide which values of lambda to use
    -nlambdas = 10
    -lambdas = np.logspace(-4, 2, nlambdas)
    -# create and fit a ridge regression model, testing each alpha
    -model = Ridge()
    -gridsearch = GridSearchCV(estimator=model, param_grid=dict(alpha=lambdas))
    -gridsearch.fit(X_train, y_train)
    -print(gridsearch)
    -ypredictRidge = gridsearch.predict(X_test)
    -# summarize the results of the grid search
    -print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}")
    -print(f"MSE score: {MSE(y_test,ypredictRidge)}")
    -print(f"R2 score: {R2(y_test,ypredictRidge)}")
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    By default the grid search function includes cross validation with -five folds. The Scikit-Learn -documentation -contains more information on how to set the different parameters. -

    - -

    If we take out the random noise, running the above codes results in \( \lambda=0 \) yielding the best fit.

    - -









    - - -

    An alternative to the above manual grid set up, is to use a random -search where the parameters are tuned from a random distribution -(uniform below) for a fixed number of iterations. A model is -constructed and evaluated for each combination of chosen parameters. -We repeat the previous example but now with a random search. Note -that values of \( \lambda \) are now limited to be within \( x\in -[0,1] \). This domain may not be the most relevant one for the specific -case under study. -

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import GridSearchCV
    -from scipy.stats import uniform as randuniform
    -from sklearn.model_selection import RandomizedSearchCV
    -
    -
    -def R2(y_data, y_model):
    -    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(2021)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -param_grid = {'alpha': randuniform()}
    -# create and fit a ridge regression model, testing each alpha
    -model = Ridge()
    -gridsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)
    -gridsearch.fit(X_train, y_train)
    -print(gridsearch)
    -ypredictRidge = gridsearch.predict(X_test)
    -# summarize the results of the grid search
    -print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}")
    -print(f"MSE score: {MSE(y_test,ypredictRidge)}")
    -print(f"R2 score: {R2(y_test,ypredictRidge)}")
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -









    Optimization, the central part of any Machine Learning algortithm

    @@ -1770,14 +1596,6 @@ plt.show()
  • GD treats all directions in parameter space uniformly. Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive.
  • GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.
  • -









    -

    Challenge yourself

    - -

    Write a code which implements gradient descent for a logistic regression example.

    - -









    -

    Friday September 30

    -









    Stochastic Gradient Descent

    @@ -2164,6 +1982,1460 @@ plt.show() +









    +

    Overview video on Stochastic Gradient Descent

    + +What is Stochastic Gradient Descent + +









    +

    Batches and mini-batches

    + +

    In gradient descent we compute the cost function and its gradient for all data points we have.

    + +

    In large-scale applications such as the ILSVRC challenge, the +training data can have on order of millions of examples. Hence, it +seems wasteful to compute the full cost function over the entire +training set in order to perform only a single parameter update. A +very common approach to addressing this challenge is to compute the +gradient over batches of the training data. For example, in current +a typical batch could contain some thousand examples from +an entire training set of several millions. This batch is then used to +perform a parameter update. +

    + +









    +

    Stochastic Gradient Descent (SGD)

    + +

    In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set. +

    + +

    This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. +

    + +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    + +









    +

    Stochastic Gradient Descent

    + +

    Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. +

    + +

    The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

    +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + + +









    +

    Computation of gradients

    + +

    This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +

    +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

    Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). +

    + +









    +

    SGD example

    + +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). +

    + +

    The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +

    +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ + + +









    +

    The gradient step

    + +

    Thus a gradient descent step now looks like

    +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ + +

    where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. +

    + +









    +

    Simple example code

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each mini-batche
    +m = int(n/M) #number of minibatches
    +n_epochs = 10 #number of epochs
    +
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for 
    +        j += 1
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. +

    + +









    +

    When do we stop?

    + +

    A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. +

    + +









    +

    Slightly different approach

    + +

    Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. +

    + +

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    + +

    In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +def step_length(t,t0,t1):
    +    return t0/(t+t1)
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 500 #number of epochs
    +t0 = 1.0
    +t1 = 10
    +
    +gamma_j = t0/t1
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for beta
    +        t = epoch*m+i
    +        gamma_j = step_length(t,t0,t1)
    +        j += 1
    +
    +print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters \( t_0 \) and \( t_1 \).

    + +









    +

    Program for stochastic gradient

    + + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +# 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 = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Replace or not

    + +

    In the above code, we have use replacement in setting up the +mini-batches. The discussion +here may be +useful. More material will be added later. +

    + +









    +

    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 +

    + +$$ +\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, Root Mean Squared Propagation (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

    + + +

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









    +

    Using Autograd with OLS

    + +

    We conclude the part on optmization by showing how we can make codes +for linear regression and logistic regression using autograd. The +first example shows results with ordinary leats squares. +

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +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.pinv(XT_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
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    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)
    +
    +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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Including Stochastic Gradient Descent with Autograd

    +

    In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using autograd.

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +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.pinv(XT_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
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    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)
    +
    +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()
    +
    +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 = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    And Logistic Regression

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +from autograd import grad
    +
    +def sigmoid(x):
    +    return 0.5 * (np.tanh(x / 2.) + 1)
    +
    +def logistic_predictions(weights, inputs):
    +    # Outputs probability of a label being true according to logistic model.
    +    return sigmoid(np.dot(inputs, weights))
    +
    +def training_loss(weights):
    +    # Training loss is the negative log-likelihood of the training labels.
    +    preds = logistic_predictions(weights, inputs)
    +    label_probabilities = preds * targets + (1 - preds) * (1 - targets)
    +    return -np.sum(np.log(label_probabilities))
    +
    +# Build a toy dataset.
    +inputs = np.array([[0.52, 1.12,  0.77],
    +                   [0.88, -1.08, 0.15],
    +                   [0.52, 0.06, -1.30],
    +                   [0.74, -2.49, 1.39]])
    +targets = np.array([True, True, False, True])
    +
    +# Define a function that returns gradients of training loss using Autograd.
    +training_gradient_fun = grad(training_loss)
    +
    +# Optimize weights using gradient descent.
    +weights = np.array([0.0, 0.0, 0.0])
    +print("Initial loss:", training_loss(weights))
    +for i in range(100):
    +    weights -= training_gradient_fun(weights) * 0.01
    +
    +print("Trained loss:", training_loss(weights))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    © 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license diff --git a/doc/pub/week39/html/week39.html b/doc/pub/week39/html/week39.html index 18205bfe7..c817c9cf9 100644 --- a/doc/pub/week39/html/week39.html +++ b/doc/pub/week39/html/week39.html @@ -142,12 +142,6 @@ div.toc p,a { {'highest level': 2, 'sections': [('Plan for week 39', 2, None, 'plan-for-week-39'), ('Thursday September 29', 2, None, 'thursday-september-29'), - ('Searching for Optimal Regularization Parameters $\\lambda$', - 2, - None, - 'searching-for-optimal-regularization-parameters-lambda'), - ('Grid Search', 2, None, 'grid-search'), - ('Randomized Grid Search', 2, None, 'randomized-grid-search'), ('Optimization, the central part of any Machine Learning ' 'algortithm', 2, @@ -263,8 +257,6 @@ div.toc p,a { 2, None, 'using-gradient-descent-methods-limitations'), - ('Challenge yourself', 2, None, 'challenge-yourself'), - ('Friday September 30', 2, None, 'friday-september-30'), ('Stochastic Gradient Descent', 2, None, @@ -285,7 +277,80 @@ div.toc p,a { ('Code with a Number of Minibatches which varies', 2, None, - 'code-with-a-number-of-minibatches-which-varies')]} + 'code-with-a-number-of-minibatches-which-varies'), + ('Overview video on Stochastic Gradient Descent', + 2, + None, + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', + 2, + None, + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', + 2, + None, + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', + 2, + None, + 'slightly-different-approach'), + ('Program for stochastic gradient', + 2, + None, + 'program-for-stochastic-gradient'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', + 2, + None, + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', + 2, + None, + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('ADAM optimizer', 2, None, 'adam-optimizer'), + ('Practical tips', 2, None, 'practical-tips'), + ('Automatic differentiation', + 2, + None, + 'automatic-differentiation'), + ('Using autograd', 2, None, 'using-autograd'), + ('Autograd with more complicated functions', + 2, + None, + 'autograd-with-more-complicated-functions'), + ('More complicated functions using the elements of their ' + 'arguments directly', + 2, + None, + 'more-complicated-functions-using-the-elements-of-their-arguments-directly'), + ('Functions using mathematical functions from Numpy', + 2, + None, + 'functions-using-mathematical-functions-from-numpy'), + ('More autograd', 2, None, 'more-autograd'), + ('And with loops', 2, None, 'and-with-loops'), + ('Using recursion', 2, None, 'using-recursion'), + ('Unsupported functions', 2, None, 'unsupported-functions'), + ('The syntax a.dot(b) when finding the dot product', + 2, + None, + 'the-syntax-a-dot-b-when-finding-the-dot-product'), + ('Recommended to avoid', 2, None, 'recommended-to-avoid'), + ('Using Autograd with OLS', 2, None, 'using-autograd-with-ols'), + ('Including Stochastic Gradient Descent with Autograd', + 2, + None, + 'including-stochastic-gradient-descent-with-autograd'), + ('And Logistic Regression', 2, None, 'and-logistic-regression')]} end of tocinfo --> @@ -319,11 +384,11 @@ MathJax.Hub.Config({ [1] Department of Physics, University of Oslo
    -[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University

    -

    Aug 23, 2022

    +

    Sep 26, 2022


    @@ -331,15 +396,17 @@ MathJax.Hub.Config({

    Plan for week 39

    See lecture notes for week 39. -For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well. +For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well.

    -For project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.55 and 5.7-5.11. +

    For Stochastic Gradient Descent, we recommend chapter 4 of Geron's text.

    + +For project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.5 and 5.7-5.11.

    These sections summarize neatly what we have done till now and point to what is coming with respect to deep learning.











    @@ -347,247 +414,6 @@ For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 Overview Video, why do we care about gradient methods? -









    -

    Searching for Optimal Regularization Parameters \( \lambda \)

    - -

    In project 1, when using Ridge and Lasso regression, we end up -searching for the optimal parameter \( \lambda \) which minimizes our -selected scores (MSE or \( R2 \) values for example). The brute force -approach, as discussed in the code here for Ridge regression, consists -in evaluating the MSE as function of different \( \lambda \) values. -Based on these calculations, one tries then to determine the value of the hyperparameter \( \lambda \) -which results in optimal scores (for example the smallest MSE or an \( R2=1 \)). -

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(2021)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -MSERidgePredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-4, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    RegRidge = linear_model.Ridge(lmb)
    -    RegRidge.fit(X_train,y_train)
    -    ypredictRidge = RegRidge.predict(X_test)
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Here we have performed a rather data greedy calculation as function of the regularization parameter \( \lambda \). There is no resampling here. The latter can easily be added by employing the function RidgeCV instead of just calling the Ridge function. For RidgeCV we need to pass the array of \( \lambda \) values. -By inspecting the figure we can in turn determine which is the optimal regularization parameter. -This becomes however less functional in the long run. -

    - -









    - - -

    An alternative is to use the so-called grid search functionality -included with the library Scikit-Learn, as demonstrated for the same -example here. -

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import GridSearchCV
    -
    -def R2(y_data, y_model):
    -    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(2021)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -# Decide which values of lambda to use
    -nlambdas = 10
    -lambdas = np.logspace(-4, 2, nlambdas)
    -# create and fit a ridge regression model, testing each alpha
    -model = Ridge()
    -gridsearch = GridSearchCV(estimator=model, param_grid=dict(alpha=lambdas))
    -gridsearch.fit(X_train, y_train)
    -print(gridsearch)
    -ypredictRidge = gridsearch.predict(X_test)
    -# summarize the results of the grid search
    -print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}")
    -print(f"MSE score: {MSE(y_test,ypredictRidge)}")
    -print(f"R2 score: {R2(y_test,ypredictRidge)}")
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    By default the grid search function includes cross validation with -five folds. The Scikit-Learn -documentation -contains more information on how to set the different parameters. -

    - -

    If we take out the random noise, running the above codes results in \( \lambda=0 \) yielding the best fit.

    - -









    - - -

    An alternative to the above manual grid set up, is to use a random -search where the parameters are tuned from a random distribution -(uniform below) for a fixed number of iterations. A model is -constructed and evaluated for each combination of chosen parameters. -We repeat the previous example but now with a random search. Note -that values of \( \lambda \) are now limited to be within \( x\in -[0,1] \). This domain may not be the most relevant one for the specific -case under study. -

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import GridSearchCV
    -from scipy.stats import uniform as randuniform
    -from sklearn.model_selection import RandomizedSearchCV
    -
    -
    -def R2(y_data, y_model):
    -    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -
    -def MSE(y_data,y_model):
    -    n = np.size(y_model)
    -    return np.sum((y_data-y_model)**2)/n
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(2021)
    -
    -n = 100
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((n,Maxpolydegree-1))
    -
    -for degree in range(1,Maxpolydegree): #No intercept column
    -    X[:,degree-1] = x**(degree)
    -
    -# We split the data in test and training data
    -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    -
    -param_grid = {'alpha': randuniform()}
    -# create and fit a ridge regression model, testing each alpha
    -model = Ridge()
    -gridsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)
    -gridsearch.fit(X_train, y_train)
    -print(gridsearch)
    -ypredictRidge = gridsearch.predict(X_test)
    -# summarize the results of the grid search
    -print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}")
    -print(f"MSE score: {MSE(y_test,ypredictRidge)}")
    -print(f"R2 score: {R2(y_test,ypredictRidge)}")
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -









    Optimization, the central part of any Machine Learning algortithm

    @@ -1847,14 +1673,6 @@ plt.show()
  • GD treats all directions in parameter space uniformly. Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive.
  • GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.
  • -









    -

    Challenge yourself

    - -

    Write a code which implements gradient descent for a logistic regression example.

    - -









    -

    Friday September 30

    -









    Stochastic Gradient Descent

    @@ -2241,6 +2059,1460 @@ plt.show() +









    +

    Overview video on Stochastic Gradient Descent

    + +What is Stochastic Gradient Descent + +









    +

    Batches and mini-batches

    + +

    In gradient descent we compute the cost function and its gradient for all data points we have.

    + +

    In large-scale applications such as the ILSVRC challenge, the +training data can have on order of millions of examples. Hence, it +seems wasteful to compute the full cost function over the entire +training set in order to perform only a single parameter update. A +very common approach to addressing this challenge is to compute the +gradient over batches of the training data. For example, in current +a typical batch could contain some thousand examples from +an entire training set of several millions. This batch is then used to +perform a parameter update. +

    + +









    +

    Stochastic Gradient Descent (SGD)

    + +

    In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set. +

    + +

    This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. +

    + +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    + +









    +

    Stochastic Gradient Descent

    + +

    Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. +

    + +

    The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

    +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + + +









    +

    Computation of gradients

    + +

    This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +

    +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

    Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). +

    + +









    +

    SGD example

    + +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). +

    + +

    The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +

    +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ + + +









    +

    The gradient step

    + +

    Thus a gradient descent step now looks like

    +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ + +

    where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. +

    + +









    +

    Simple example code

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each mini-batche
    +m = int(n/M) #number of minibatches
    +n_epochs = 10 #number of epochs
    +
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for 
    +        j += 1
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. +

    + +









    +

    When do we stop?

    + +

    A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. +

    + +









    +

    Slightly different approach

    + +

    Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. +

    + +

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    + +

    In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +def step_length(t,t0,t1):
    +    return t0/(t+t1)
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 500 #number of epochs
    +t0 = 1.0
    +t1 = 10
    +
    +gamma_j = t0/t1
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for beta
    +        t = epoch*m+i
    +        gamma_j = step_length(t,t0,t1)
    +        j += 1
    +
    +print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters \( t_0 \) and \( t_1 \).

    + +









    +

    Program for stochastic gradient

    + + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +# 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 = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Replace or not

    + +

    In the above code, we have use replacement in setting up the +mini-batches. The discussion +here may be +useful. More material will be added later. +

    + +









    +

    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 +

    + +$$ +\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, Root Mean Squared Propagation (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

    + + +

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









    +

    Using Autograd with OLS

    + +

    We conclude the part on optmization by showing how we can make codes +for linear regression and logistic regression using autograd. The +first example shows results with ordinary leats squares. +

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +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.pinv(XT_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
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    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)
    +
    +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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Including Stochastic Gradient Descent with Autograd

    +

    In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using autograd.

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +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.pinv(XT_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
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    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)
    +
    +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()
    +
    +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 = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    And Logistic Regression

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +from autograd import grad
    +
    +def sigmoid(x):
    +    return 0.5 * (np.tanh(x / 2.) + 1)
    +
    +def logistic_predictions(weights, inputs):
    +    # Outputs probability of a label being true according to logistic model.
    +    return sigmoid(np.dot(inputs, weights))
    +
    +def training_loss(weights):
    +    # Training loss is the negative log-likelihood of the training labels.
    +    preds = logistic_predictions(weights, inputs)
    +    label_probabilities = preds * targets + (1 - preds) * (1 - targets)
    +    return -np.sum(np.log(label_probabilities))
    +
    +# Build a toy dataset.
    +inputs = np.array([[0.52, 1.12,  0.77],
    +                   [0.88, -1.08, 0.15],
    +                   [0.52, 0.06, -1.30],
    +                   [0.74, -2.49, 1.39]])
    +targets = np.array([True, True, False, True])
    +
    +# Define a function that returns gradients of training loss using Autograd.
    +training_gradient_fun = grad(training_loss)
    +
    +# Optimize weights using gradient descent.
    +weights = np.array([0.0, 0.0, 0.0])
    +print("Initial loss:", training_loss(weights))
    +for i in range(100):
    +    weights -= training_gradient_fun(weights) * 0.01
    +
    +print("Trained loss:", training_loss(weights))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    © 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license diff --git a/doc/pub/week39/ipynb/ipynb-week39-src.tar.gz b/doc/pub/week39/ipynb/ipynb-week39-src.tar.gz index 2e1f0e302944601cc3062a5c7551354a1699c112..a07bbc21cf42f32d01213b36c63bf63ce3b85a43 100644 GIT binary patch literal 193 zcmV;y06za8iwFS5Eiq#N1MSaC3c@fD2H>uHia9|^nl#0wU>7a~5igL^)W+JRCMnw6 z+Xv`MaZ^OdxA_@n7-kOHdb7(ScXz>J5JHSn7&B$blqjC-3C0OvN-&LMmLdiSlZ2oE z&~hiebk=b*oYGWhp{!8v=7zDd{IF+!1)ljQj+L~q-S@823Y2yt*SdzA5H(pvvh7t4 vg%);fff3hE8UbAOz>7jUsTIG3tZ~RrOh#00;m8On6v0 literal 191 zcmV;w06_mAiwFSulLTV`1MSbv3c@f92XN1Oiafz++!r1Nckm#H_yQfvT%BuY+o5}V z_W^oRybKZgyZi|WAvvV$%`Wxr-7aRs7>mOYhD_pUOtzfr5n==w27MwX2?E0)!ejw# zzLQ>BW4Z26smn7-L-O5RKUNeU_Drw9GylY~6b82Y&X!7oRF*QOD!36 0$ be two fixed numbers. Furthermore, let $t = e \\cdot m + i$ where $m$ is the number of minibatches and $i=0,\\cdots,m-1$. Then the function $$\\gamma_j(t; t_0, t_1) = \\frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$.\n", + "\n", + "In this way we can fix the number of epochs, compute $\\beta$ and\n", + "evaluate the cost function at the end. Repeating the computation will\n", + "give a different result since the scheme is random by design. Then we\n", + "pick the final $\\beta$ that gives the lowest value of the cost\n", + "function." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "78e602eb", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np \n", + "\n", + "def step_length(t,t0,t1):\n", + " return t0/(t+t1)\n", + "\n", + "n = 100 #100 datapoints \n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "n_epochs = 500 #number of epochs\n", + "t0 = 1.0\n", + "t1 = 10\n", + "\n", + "gamma_j = t0/t1\n", + "j = 0\n", + "for epoch in range(1,n_epochs+1):\n", + " for i in range(m):\n", + " k = np.random.randint(m) #Pick the k-th minibatch at random\n", + " #Compute the gradient using the data in minibatch Bk\n", + " #Compute new suggestion for beta\n", + " t = epoch*m+i\n", + " gamma_j = step_length(t,t0,t1)\n", + " j += 1\n", + "\n", + "print(\"gamma_j after %d epochs: %g\" % (n_epochs,gamma_j))" + ] + }, + { + "cell_type": "markdown", + "id": "d3d5fdfc", + "metadata": { + "editable": true + }, + "source": [ + "We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters $t_0$ and $t_1$." + ] + }, + { + "cell_type": "markdown", + "id": "2d89fdc5", + "metadata": { + "editable": true + }, + "source": [ + "## Program for stochastic gradient" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "5bd4ddd0", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "# 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 = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+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", + "\n", + "\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()" + ] + }, + { + "cell_type": "markdown", + "id": "906ca8a3", + "metadata": { + "editable": true + }, + "source": [ + "## Replace or not\n", + "\n", + "In the above code, we have use replacement in setting up the\n", + "mini-batches. The discussion\n", + "[here](https://sebastianraschka.com/faq/docs/sgd-methods.html) may be\n", + "useful. More material will be added later." + ] + }, + { + "cell_type": "markdown", + "id": "4a184020", + "metadata": { + "editable": true + }, + "source": [ + "## Momentum based GD\n", + "\n", + "The stochastic gradient descent (SGD) is almost always used with a\n", + "*momentum* or inertia term that serves as a memory of the direction we\n", + "are moving in parameter space. This is typically implemented as\n", + "follows" + ] + }, + { + "cell_type": "markdown", + "id": "02d4f63f", + "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": "8c5143d0", + "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": "037205df", + "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": "e3dcc6e8", + "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": "d9a353dd", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." + ] + }, + { + "cell_type": "markdown", + "id": "473055d4", + "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": "35e67283", + "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": "bf92c54d", + "metadata": { + "editable": true + }, + "source": [ + "We can discretize this equation in the usual way to get" + ] + }, + { + "cell_type": "markdown", + "id": "f2541cad", + "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": "1520d357", + "metadata": { + "editable": true + }, + "source": [ + "Rearranging this equation, we can rewrite this as" + ] + }, + { + "cell_type": "markdown", + "id": "102449f7", + "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": "0fbe4820", + "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": "b163b029", + "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": "17f8c54e", + "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": "c5e2273f", + "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": "96ee109a", + "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": "eb0b51e1", + "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": "1140b00b", + "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, Root Mean Squared Propagation (RMS-Prop), and\n", + "ADAM." + ] + }, + { + "cell_type": "markdown", + "id": "12e8dbaa", + "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": "05867c79", + "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": "47c4750f", + "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": "2f18c06e", + "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": "d00446d9", + "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": "bc5f3776", + "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": "f3071815", + "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": "aac9b1f4", + "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": "14b3cf69", + "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": "1762335e", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "07235a77", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5060ad05", + "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": "7b4d96d7", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
    \n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\label{_auto5} \\tag{6}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a4c384f5", + "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": "2c3d8429", + "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": "b5857328", + "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": "06b5c926", + "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": "721bf584", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "49d791e1", + "metadata": { + "editable": true + }, + "source": [ + "which has the following derivative" + ] + }, + { + "cell_type": "markdown", + "id": "9c676f72", + "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": "2055fb52", + "metadata": { + "editable": true + }, + "source": [ + "Using **autograd** we have" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "eca0da75", + "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": "5dae5aba", + "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": 18, + "id": "d0790e9f", + "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": "84ee3863", + "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": 19, + "id": "51d09008", + "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": "2d8e4407", + "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": "30ad2970", + "metadata": { + "editable": true + }, + "source": [ + "## More complicated functions using the elements of their arguments directly" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "8e8e65cf", + "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": "3aca489a", + "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": "6c20bd49", + "metadata": { + "editable": true + }, + "source": [ + "## Functions using mathematical functions from Numpy" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "d002c399", + "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": "a933898e", + "metadata": { + "editable": true + }, + "source": [ + "## More autograd" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "387235f0", + "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": "3cc26abd", + "metadata": { + "editable": true + }, + "source": [ + "## And with loops" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "b1dd069d", + "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": 24, + "id": "baf90cb4", + "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": "0eff5efe", + "metadata": { + "editable": true + }, + "source": [ + "## Using recursion" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "37b54f99", + "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": "3fd3588a", + "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": "bba43464", + "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": 26, + "id": "534ccb45", + "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": "97bdc2ce", + "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": "a914c4e0", + "metadata": { + "editable": true + }, + "source": [ + "## The syntax a.dot(b) when finding the dot product" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "b00a4fd5", + "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": "665e48d5", + "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": 28, + "id": "a33a6436", + "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": "a564dc5a", + "metadata": { + "editable": true + }, + "source": [ + "## Recommended to avoid\n", + "The documentation recommends to avoid inplace operations such as" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "eab6652e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "a += b\n", + "a -= b\n", + "a*= b\n", + "a /=b" + ] + }, + { + "cell_type": "markdown", + "id": "74647197", + "metadata": { + "editable": true + }, + "source": [ + "## Using Autograd with OLS\n", + "\n", + "We conclude the part on optmization by showing how we can make codes\n", + "for linear regression and logistic regression using **autograd**. The\n", + "first example shows results with ordinary leats squares." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "264a6c11", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients for OLS\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\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.pinv(XT_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", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(theta)\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", + "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()" + ] + }, + { + "cell_type": "markdown", + "id": "e9cf7f42", + "metadata": { + "editable": true + }, + "source": [ + "## Including Stochastic Gradient Descent with Autograd\n", + "In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using **autograd**." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "86d059a4", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using SGD\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\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.pinv(XT_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", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = (1.0/n)*training_gradient(y, X, theta)\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", + "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()\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 = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "0d1ea9d0", + "metadata": { + "editable": true + }, + "source": [ + "## And Logistic Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "4dc2352d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "\n", + "def sigmoid(x):\n", + " return 0.5 * (np.tanh(x / 2.) + 1)\n", + "\n", + "def logistic_predictions(weights, inputs):\n", + " # Outputs probability of a label being true according to logistic model.\n", + " return sigmoid(np.dot(inputs, weights))\n", + "\n", + "def training_loss(weights):\n", + " # Training loss is the negative log-likelihood of the training labels.\n", + " preds = logistic_predictions(weights, inputs)\n", + " label_probabilities = preds * targets + (1 - preds) * (1 - targets)\n", + " return -np.sum(np.log(label_probabilities))\n", + "\n", + "# Build a toy dataset.\n", + "inputs = np.array([[0.52, 1.12, 0.77],\n", + " [0.88, -1.08, 0.15],\n", + " [0.52, 0.06, -1.30],\n", + " [0.74, -2.49, 1.39]])\n", + "targets = np.array([True, True, False, True])\n", + "\n", + "# Define a function that returns gradients of training loss using Autograd.\n", + "training_gradient_fun = grad(training_loss)\n", + "\n", + "# Optimize weights using gradient descent.\n", + "weights = np.array([0.0, 0.0, 0.0])\n", + "print(\"Initial loss:\", training_loss(weights))\n", + "for i in range(100):\n", + " weights -= training_gradient_fun(weights) * 0.01\n", + "\n", + "print(\"Trained loss:\", training_loss(weights))" + ] } ], "metadata": {}, diff --git a/doc/src/week39/week39.do.txt b/doc/src/week39/week39.do.txt index 8052c2fba..6d0bd00af 100644 --- a/doc/src/week39/week39.do.txt +++ b/doc/src/week39/week39.do.txt @@ -1,19 +1,21 @@ TITLE: Week 39: Optimization and Gradient Methods -AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University DATE: today !split ===== Plan for week 39 ===== -* Thursday: Repetition of Logistic regression equations and classification problems and discussion of Gradient methods. Discussion of project 1 and examples on how to implement Logistic Regression +* Thursday: Repetition of Logistic regression equations and classification problems and discussion of Gradient methods. Examples on how to implement Logistic Regression * Friday: Stochastic Gradient descent with examples and automatic differentiation * Reading recommendations: See "lecture notes for week 39":"https://compphysics.github.io/MachineLearning/doc/web/course.html". -For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well. +For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well. -_For project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.55 and 5.7-5.11_. +For Stochastic Gradient Descent, we recommend chapter 4 of Geron's text. + +_For project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.5 and 5.7-5.11_. These sections summarize neatly what we have done till now and point to what is coming with respect to deep learning. !split @@ -22,192 +24,6 @@ These sections summarize neatly what we have done till now and point to what is "Overview Video, why do we care about gradient methods?":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/OverarchingAimsWeek39.mp4?vrtx=view-as-webpage" -!split -===== Searching for Optimal Regularization Parameters $\lambda$ ===== - -In project 1, when using Ridge and Lasso regression, we end up -searching for the optimal parameter $\lambda$ which minimizes our -selected scores (MSE or $R2$ values for example). The brute force -approach, as discussed in the code here for Ridge regression, consists -in evaluating the MSE as function of different $\lambda$ values. -Based on these calculations, one tries then to determine the value of the hyperparameter $\lambda$ -which results in optimal scores (for example the smallest MSE or an $R2=1$). -!bc pycod -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -from sklearn import linear_model - -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(2021) - -n = 100 -x = np.random.rand(n) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n) - -Maxpolydegree = 5 -X = np.zeros((n,Maxpolydegree-1)) - -for degree in range(1,Maxpolydegree): #No intercept column - X[:,degree-1] = x**(degree) - -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) - -# Decide which values of lambda to use -nlambdas = 500 -MSERidgePredict = np.zeros(nlambdas) -lambdas = np.logspace(-4, 2, nlambdas) -for i in range(nlambdas): - lmb = lambdas[i] - RegRidge = linear_model.Ridge(lmb) - RegRidge.fit(X_train,y_train) - ypredictRidge = RegRidge.predict(X_test) - MSERidgePredict[i] = MSE(y_test,ypredictRidge) - -# Now plot the results -plt.figure() -plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test') -plt.xlabel('log10(lambda)') -plt.ylabel('MSE') -plt.legend() -plt.show() - -!ec - -Here we have performed a rather data greedy calculation as function of the regularization parameter $\lambda$. There is no resampling here. The latter can easily be added by employing the function _RidgeCV_ instead of just calling the _Ridge_ function. For _RidgeCV_ we need to pass the array of $\lambda$ values. -By inspecting the figure we can in turn determine which is the optimal regularization parameter. -This becomes however less functional in the long run. - - -!split -===== Grid Search ===== - - -An alternative is to use the so-called grid search functionality -included with the library _Scikit-Learn_, as demonstrated for the same -example here. - -!bc pycod -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.linear_model import Ridge -from sklearn.model_selection import GridSearchCV - -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) - -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(2021) - -n = 100 -x = np.random.rand(n) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n) - -Maxpolydegree = 5 -X = np.zeros((n,Maxpolydegree-1)) - -for degree in range(1,Maxpolydegree): #No intercept column - X[:,degree-1] = x**(degree) - -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) - -# Decide which values of lambda to use -nlambdas = 10 -lambdas = np.logspace(-4, 2, nlambdas) -# create and fit a ridge regression model, testing each alpha -model = Ridge() -gridsearch = GridSearchCV(estimator=model, param_grid=dict(alpha=lambdas)) -gridsearch.fit(X_train, y_train) -print(gridsearch) -ypredictRidge = gridsearch.predict(X_test) -# summarize the results of the grid search -print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}") -print(f"MSE score: {MSE(y_test,ypredictRidge)}") -print(f"R2 score: {R2(y_test,ypredictRidge)}") - -!ec - -By default the grid search function includes cross validation with -five folds. The "Scikit-Learn -documentation":"https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV" -contains more information on how to set the different parameters. - -If we take out the random noise, running the above codes results in $\lambda=0$ yielding the best fit. - - -!split -===== Randomized Grid Search ===== - -An alternative to the above manual grid set up, is to use a random -search where the parameters are tuned from a random distribution -(uniform below) for a fixed number of iterations. A model is -constructed and evaluated for each combination of chosen parameters. -We repeat the previous example but now with a random search. Note -that values of $\lambda$ are now limited to be within $x\in -[0,1]$. This domain may not be the most relevant one for the specific -case under study. - - -!bc pycod -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.linear_model import Ridge -from sklearn.model_selection import GridSearchCV -from scipy.stats import uniform as randuniform -from sklearn.model_selection import RandomizedSearchCV - - -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) - -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(2021) - -n = 100 -x = np.random.rand(n) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n) - -Maxpolydegree = 5 -X = np.zeros((n,Maxpolydegree-1)) - -for degree in range(1,Maxpolydegree): #No intercept column - X[:,degree-1] = x**(degree) - -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) - -param_grid = {'alpha': randuniform()} -# create and fit a ridge regression model, testing each alpha -model = Ridge() -gridsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100) -gridsearch.fit(X_train, y_train) -print(gridsearch) -ypredictRidge = gridsearch.predict(X_test) -# summarize the results of the grid search -print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}") -print(f"MSE score: {MSE(y_test,ypredictRidge)}") -print(f"R2 score: {R2(y_test,ypredictRidge)}") - -!ec - - !split ===== Optimization, the central part of any Machine Learning algortithm ===== @@ -1253,17 +1069,6 @@ plt.show() * GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points. -!split -===== Challenge yourself ===== - -Write a code which implements gradient descent for a logistic regression example. - - - - -!split -===== Friday September 30 ===== - !split ===== Stochastic Gradient Descent ===== @@ -1577,3 +1382,1087 @@ plt.show() !ec + + + +!split +===== Overview video on Stochastic Gradient Descent ===== + +"What is Stochastic Gradient Descent":"https://www.youtube.com/watch?v=vMh0zPT0tLI&ab_channel=StatQuestwithJoshStarmer" + + +!split +===== Batches and mini-batches ===== + +In gradient descent we compute the cost function and its gradient for all data points we have. + +In large-scale applications such as the "ILSVRC challenge":"https://www.image-net.org/challenges/LSVRC/", the +training data can have on order of millions of examples. Hence, it +seems wasteful to compute the full cost function over the entire +training set in order to perform only a single parameter update. A +very common approach to addressing this challenge is to compute the +gradient over batches of the training data. For example, in current +a typical batch could contain some thousand examples from +an entire training set of several millions. This batch is then used to +perform a parameter update. + +!split +===== Stochastic Gradient Descent (SGD) ===== + +In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set. + +This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. + +In our notes with SGD we mean stochastic gradient descent with mini-batches. + + +!split +===== Stochastic Gradient Descent ===== + +Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. + +The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over $n$ data points $\{\mathbf{x}_i\}_{i=1}^n$, +!bt +\[ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +\] +!et + +!split +===== Computation of gradients ===== + +This in turn means that the gradient can be +computed as a sum over $i$-gradients +!bt +\[ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +\] +!et + +Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are $n$ +data points and the size of each minibatch is $M$, there will be $n/M$ +minibatches. We denote these minibatches by $B_k$ where +$k=1,\cdots,n/M$. + +!split +===== SGD example ===== + +As an example, suppose we have $10$ data points $(\mathbf{x}_1,\cdots, \mathbf{x}_{10})$ +and we choose to have $M=5$ minibathces, +then each minibatch contains two data points. In particular we have +$B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10})$. Note that if you choose $M=1$ you +have only a single batch with all data points and on the other extreme, +you may choose $M=n$ resulting in a minibatch for each datapoint, i.e +$B_k = \mathbf{x}_k$. + +The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +!bt +\[ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +\] +!et + +!split +===== The gradient step ===== + +Thus a gradient descent step now looks like +!bt +\[ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +\] +!et + +where $k$ is picked at random with equal +probability from $[1,n/M]$. An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. + +!split +===== Simple example code ===== + +!bc pycod +import numpy as np + +n = 100 #100 datapoints +M = 5 #size of each mini-batche +m = int(n/M) #number of minibatches +n_epochs = 10 #number of epochs + +j = 0 +for epoch in range(1,n_epochs+1): + for i in range(m): + k = np.random.randint(m) #Pick the k-th minibatch at random + #Compute the gradient using the data in minibatch Bk + #Compute new suggestion for + j += 1 +!ec + +Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints ($M < n$), the computation of the gradient is much +cheaper since we sum over the datapoints in the $k-th$ minibatch and not +all $n$ datapoints. + +!split +===== When do we stop? ===== + +A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the $\beta$ that +gave the lowest value. + +!split +===== Slightly different approach ===== + +Another approach is to let the step length $\gamma_j$ depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. + +As an example, let $e = 0,1,2,3,\cdots$ denote the current epoch and let $t_0, t_1 > 0$ be two fixed numbers. Furthermore, let $t = e \cdot m + i$ where $m$ is the number of minibatches and $i=0,\cdots,m-1$. Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$. + +In this way we can fix the number of epochs, compute $\beta$ and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final $\beta$ that gives the lowest value of the cost +function. + +!bc pycod +import numpy as np + +def step_length(t,t0,t1): + return t0/(t+t1) + +n = 100 #100 datapoints +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +n_epochs = 500 #number of epochs +t0 = 1.0 +t1 = 10 + +gamma_j = t0/t1 +j = 0 +for epoch in range(1,n_epochs+1): + for i in range(m): + k = np.random.randint(m) #Pick the k-th minibatch at random + #Compute the gradient using the data in minibatch Bk + #Compute new suggestion for beta + t = epoch*m+i + gamma_j = step_length(t,t0,t1) + j += 1 + +print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j)) +!ec + + +We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters $t_0$ and $t_1$. + + +!split +===== Program for stochastic gradient ===== + +!bc pycod +# Importing various packages +# 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 = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+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() + +!ec + +!split +===== Replace or not ===== + +In the above code, we have use replacement in setting up the +mini-batches. The discussion +"here":"https://sebastianraschka.com/faq/docs/sgd-methods.html" may be +useful. More material will be added later. + + +!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, Root Mean Squared Propagation (RMS-Prop), and +ADAM. + +!split +===== RMS prop ===== + +In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by $\mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2]$. The update rule +for RMS prop is given by + +!bt +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) \\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +!et + +where $\beta$ controls the averaging time of the second moment and is +typically taken to be about $\beta=0.9$, $\eta_t$ is a learning rate +typically chosen to be $10^{-3}$, and $\epsilon\sim 10^{-8} $ is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions. + + +!split +===== ADAM optimizer ===== + +A related algorithm is the ADAM optimizer. In ADAM, we keep a running +average of both the first and second moment of the gradient and use +this information to adaptively change the learning rate for different +parameters. In addition to keeping a running average of the first and +second moments of the gradient +(i.e. $\mathbf{m}_t=\mathbb{E}[\mathbf{g}_t]$ and +$\mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t]$, respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below) + +!bt +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) \\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\bm{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\bm{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \bm{\mathbf{m}}_t \over \sqrt{\bm{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\end{align} +!et + +where $\beta_1$ and $\beta_2$ set the memory lifetime of the first and +second moment and are typically taken to be $0.9$ and $0.99$ +respectively, and $\eta$ and $\epsilon$ are identical to RMSprop. + +Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +$\boldsymbol{\sigma}_t^2 = \bm{\mathbf{s}}_t - +(\bm{\mathbf{m}}_t)^2$. Consider a single parameter $\theta_t$. The +update rule for this parameter is given by + +!bt +\[ +\Delta \theta_{t+1}= -\eta_t { \bm{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +\] +!et + + + + +!split +===== Practical tips ===== + +* _Randomize the data when making mini-batches_. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented. + +* _Transform your inputs_. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case. + +* _Monitor the out-of-sample performance._ Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings. + +* _Adaptive optimization methods don't always have good generalization._ Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications. + +Geron's text, see chapter 11, has several interesting discussions. + + + +!split +===== Automatic differentiation ===== + +"Automatic differentiation (AD)":"https://en.wikipedia.org/wiki/Automatic_differentiation", +also called algorithmic +differentiation or computational differentiation,is a set of +techniques to numerically evaluate the derivative of a function +specified by a computer program. AD exploits the fact that every +computer program, no matter how complicated, executes a sequence of +elementary arithmetic operations (addition, subtraction, +multiplication, division, etc.) and elementary functions (exp, log, +sin, cos, etc.). By applying the chain rule repeatedly to these +operations, derivatives of arbitrary order can be computed +automatically, accurately to working precision, and using at most a +small constant factor more arithmetic operations than the original +program. + +Automatic differentiation is neither: + +* Symbolic differentiation, nor +* Numerical differentiation (the method of finite differences). + +Symbolic differentiation can lead to inefficient code and faces the +difficulty of converting a computer program into a single expression, +while numerical differentiation can introduce round-off errors in the +discretization process and cancellation + + + +Python has tools for so-called _automatic differentiation_. +Consider the following example +!bt +\[ +f(x) = \sin\left(2\pi x + x^2\right) +\] +!et +which has the following derivative +!bt +\[ +f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right) +\] +!et +Using _autograd_ we have + +!bc pycod +import autograd.numpy as np + +# To do elementwise differentiation: +from autograd import elementwise_grad as egrad + +# To plot: +import matplotlib.pyplot as plt + + +def f(x): + return np.sin(2*np.pi*x + x**2) + +def f_grad_analytic(x): + return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x) + +# Do the comparison: +x = np.linspace(0,1,1000) + +f_grad = egrad(f) + +computed = f_grad(x) +analytic = f_grad_analytic(x) + +plt.title('Derivative computed from Autograd compared with the analytical derivative') +plt.plot(x,computed,label='autograd') +plt.plot(x,analytic,label='analytic') + +plt.xlabel('x') +plt.ylabel('y') +plt.legend() + +plt.show() + +print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic)))) +!ec + +!split +===== Using autograd ===== + +Here we +experiment with what kind of functions Autograd is capable +of finding the gradient of. The following Python functions are just +meant to illustrate what Autograd can do, but please feel free to +experiment with other, possibly more complicated, functions as well. + +!bc pycod +import autograd.numpy as np +from autograd import grad + +def f1(x): + return x**3 + 1 + +f1_grad = grad(f1) + +# Remember to send in float as argument to the computed gradient from Autograd! +a = 1.0 + +# See the evaluated gradient at a using autograd: +print("The gradient of f1 evaluated at a = %g using autograd is: %g"%(a,f1_grad(a))) + +# Compare with the analytical derivative, that is f1'(x) = 3*x**2 +grad_analytical = 3*a**2 +print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical)) +!ec + + +!split +===== Autograd with more complicated functions ===== + +To differentiate with respect to two (or more) arguments of a Python +function, Autograd need to know at which variable the function if +being differentiated with respect to. + +!bc pycod +import autograd.numpy as np +from autograd import grad +def f2(x1,x2): + return 3*x1**3 + x2*(x1 - 5) + 1 + +# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1 +f2_grad_x1 = grad(f2,0) + +# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad +f2_grad_x2 = grad(f2,1) + +x1 = 1.0 +x2 = 3.0 + +print("Evaluating at x1 = %g, x2 = %g"%(x1,x2)) +print("-"*30) + +# Compare with the analytical derivatives: + +# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2: +f2_grad_x1_analytical = 9*x1**2 + x2 + +# Derivative of f2 w.r.t x2 is: x1 - 5: +f2_grad_x2_analytical = x1 - 5 + +# See the evaluated derivations: +print("The derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) )) +print("The analytical derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) )) + +print() + +print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) )) +print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) )) +!ec + +Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable. + + +!split +===== More complicated functions using the elements of their arguments directly ===== + +!bc pycod +import autograd.numpy as np +from autograd import grad +def f3(x): # Assumes x is an array of length 5 or higher + return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2 + +f3_grad = grad(f3) + +x = np.linspace(0,4,5) + +# Print the computed gradient: +print("The computed gradient of f3 is: ", f3_grad(x)) + +# The analytical gradient is: (2, 3, 5, 7, 22*x[4]) +f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]]) + +# Print the analytical gradient: +print("The analytical gradient of f3 is: ", f3_grad_analytical) +!ec + +Note that in this case, when sending an array as input argument, the +output from Autograd is another array. This is the true gradient of +the function, as opposed to the function in the previous example. By +using arrays to represent the variables, the output from Autograd +might be easier to work with, as the output is closer to what one +could expect form a gradient-evaluting function. + +!split +===== Functions using mathematical functions from Numpy ===== + +!bc pycod +import autograd.numpy as np +from autograd import grad +def f4(x): + return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x) + +f4_grad = grad(f4) + +x = 2.7 + +# Print the computed derivative: +print("The computed derivative of f4 at x = %g is: %g"%(x,f4_grad(x))) + +# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi +f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi + +# Print the analytical gradient: +print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical)) +!ec + + +!split +===== More autograd ===== + +!bc pycod +import autograd.numpy as np +from autograd import grad +def f5(x): + if x >= 0: + return x**2 + else: + return -3*x + 1 + +f5_grad = grad(f5) + +x = 2.7 + +# Print the computed derivative: +print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x))) +!ec + + +!split +===== And with loops ===== + +!bc pycod +import autograd.numpy as np +from autograd import grad +def f6_for(x): + val = 0 + for i in range(10): + val = val + x**i + return val + +def f6_while(x): + val = 0 + i = 0 + while i < 10: + val = val + x**i + i = i + 1 + return val + +f6_for_grad = grad(f6_for) +f6_while_grad = grad(f6_while) + +x = 0.5 + +# Print the computed derivaties of f6_for and f6_while +print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x))) +print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x))) +!ec +!bc pycod +import autograd.numpy as np +from autograd import grad +# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9 +# The analytical derivative is: sum(i*x**(i-1)) +f6_grad_analytical = 0 +for i in range(10): + f6_grad_analytical += i*x**(i-1) + +print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical)) +!ec + +!split +===== Using recursion ===== +!bc pycod +import autograd.numpy as np +from autograd import grad + +def f7(n): # Assume that n is an integer + if n == 1 or n == 0: + return 1 + else: + return n*f7(n-1) + +f7_grad = grad(f7) + +n = 2.0 + +print("The computed derivative of f7 at n = %d is: %g"%(n,f7_grad(n))) + +# The function f7 is an implementation of the factorial of n. +# By using the product rule, one can find that the derivative is: + +f7_grad_analytical = 0 +for i in range(int(n)-1): + tmp = 1 + for k in range(int(n)-1): + if k != i: + tmp *= (n - k) + f7_grad_analytical += tmp + +print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical)) + +!ec +Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. + +!split +===== Unsupported functions ===== +Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. + +Assigning a value to the variable being differentiated with respect to +!bc pycod +import autograd.numpy as np +from autograd import grad +def f8(x): # Assume x is an array + x[2] = 3 + return x*2 + +f8_grad = grad(f8) + +x = 8.4 + +print("The derivative of f8 is:",f8_grad(x)) +!ec +Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. + +!split +===== The syntax a.dot(b) when finding the dot product ===== +!bc pycod +import autograd.numpy as np +from autograd import grad +def f9(a): # Assume a is an array with 2 elements + b = np.array([1.0,2.0]) + return a.dot(b) + +f9_grad = grad(f9) + +x = np.array([1.0,0.0]) + +print("The derivative of f9 is:",f9_grad(x)) +!ec + +Here we are told that the 'dot' function does not belong to Autograd's +version of a Numpy array. To overcome this, an alternative syntax +which also computed the dot product can be used: + +!bc pycod +import autograd.numpy as np +from autograd import grad +def f9_alternative(x): # Assume a is an array with 2 elements + b = np.array([1.0,2.0]) + return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2 + +f9_alternative_grad = grad(f9_alternative) + +x = np.array([3.0,0.0]) + +print("The gradient of f9 is:",f9_alternative_grad(x)) + +# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively +# w.r.t x is (b_1, b_2). +!ec + +!split +===== Recommended to avoid ===== +The documentation recommends to avoid inplace operations such as +!bc pycod +a += b +a -= b +a*= b +a /=b +!ec + + +!split +===== Using Autograd with OLS ===== + +We conclude the part on optmization by showing how we can make codes +for linear regression and logistic regression using _autograd_. The +first example shows results with ordinary leats squares. + +!bc pycod +# Using Autograd to calculate gradients for OLS +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +def CostOLS(beta): + return (1.0/n)*np.sum((y-X @ beta)**2) + +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.pinv(XT_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 +# define the gradient +training_gradient = grad(CostOLS) + +for iter in range(Niterations): + gradients = training_gradient(theta) + 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) + +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() + +!ec + + +!split +===== Including Stochastic Gradient Descent with Autograd ===== +In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using _autograd_. + +!bc pycod +# Using Autograd to calculate gradients using SGD +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +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.pinv(XT_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 + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) + +for iter in range(Niterations): + gradients = (1.0/n)*training_gradient(y, X, theta) + 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) + +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() + +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 = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + eta = learning_schedule(epoch*m+i) + theta = theta - eta*gradients +print("theta from own sdg") +print(theta) + + +!ec + +!split +===== And Logistic Regression ===== + +!bc pycod +import autograd.numpy as np +from autograd import grad + +def sigmoid(x): + return 0.5 * (np.tanh(x / 2.) + 1) + +def logistic_predictions(weights, inputs): + # Outputs probability of a label being true according to logistic model. + return sigmoid(np.dot(inputs, weights)) + +def training_loss(weights): + # Training loss is the negative log-likelihood of the training labels. + preds = logistic_predictions(weights, inputs) + label_probabilities = preds * targets + (1 - preds) * (1 - targets) + return -np.sum(np.log(label_probabilities)) + +# Build a toy dataset. +inputs = np.array([[0.52, 1.12, 0.77], + [0.88, -1.08, 0.15], + [0.52, 0.06, -1.30], + [0.74, -2.49, 1.39]]) +targets = np.array([True, True, False, True]) + +# Define a function that returns gradients of training loss using Autograd. +training_gradient_fun = grad(training_loss) + +# Optimize weights using gradient descent. +weights = np.array([0.0, 0.0, 0.0]) +print("Initial loss:", training_loss(weights)) +for i in range(100): + weights -= training_gradient_fun(weights) * 0.01 + +print("Trained loss:", training_loss(weights)) +!ec + +