update week 40
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -4,10 +4,6 @@ DATE: September 29-October 3, 2025
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== Plans for week 40 =====
|
||||
|
||||
|
||||
!split
|
||||
===== Lecture Monday September 30, 2024 =====
|
||||
!bblock
|
||||
@@ -39,718 +35,6 @@ DATE: September 29-October 3, 2025
|
||||
!eblock
|
||||
|
||||
|
||||
!split
|
||||
===== Summary from last week, using gradient descent methods, limitations =====
|
||||
|
||||
* _Gradient descent (GD) finds local minima of our function_. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.
|
||||
|
||||
* _GD is sensitive to initial conditions_. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.
|
||||
|
||||
* _Gradients are computationally expensive to calculate for large datasets_. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, $E \propto \sum_{i=1}^n (y_i - \mathbf{w}^T\cdot\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called ``mini batches''. This has the added benefit of introducing stochasticity into our algorithm.
|
||||
|
||||
* _GD is very sensitive to choices of learning rates_. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape.
|
||||
|
||||
* _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.
|
||||
|
||||
!split
|
||||
===== Simple implementation of GD for OLS, Ridge and Lasso =====
|
||||
|
||||
Last week we studied both several gradient methods. With and without an update of the learning.
|
||||
We summarize some of these here for the methods we hvae studied in project one, without the inclusion of momentum.
|
||||
!bc pycod
|
||||
from random import random, seed
|
||||
import numpy as np
|
||||
|
||||
# the number of datapoints with a 2nd-order polynomial
|
||||
n = 100
|
||||
x = 2*np.random.rand(n,1)
|
||||
y = 4+3*x+5*x*x
|
||||
# Design matrix including the intercept
|
||||
# No scaling of data of and all data used for training
|
||||
X = np.c_[np.ones((n,1)), x, x*x]
|
||||
# Learning rate and number of iterations
|
||||
eta = 0.05
|
||||
Niterations = 100
|
||||
|
||||
# OLS part
|
||||
beta_OLS = np.random.randn(3,1)
|
||||
gradient = np.zeros(3)
|
||||
for iter in range(Niterations):
|
||||
gradient = (2.0/n)*X.T @ (X @ beta_OLS-y)
|
||||
beta_OLS -= eta*gradient
|
||||
print('Parameters for OLS using gradient descent')
|
||||
print(beta_OLS)
|
||||
|
||||
#Ridge and Lasso parameter Lambda
|
||||
Lambda = 0.01
|
||||
Id = n*Lambda* np.eye((X.T @ X).shape[0])
|
||||
# Gradient descent with Ridge
|
||||
beta_Ridge = np.random.randn(3,1)
|
||||
gradient = np.zeros(3)
|
||||
for iter in range(Niterations):
|
||||
gradients = 2.0/n*X.T @ (X @ beta_Ridge-y)+2*Lambda*beta_Ridge
|
||||
beta_Ridge -= eta*gradients
|
||||
print('Parameters for Ridge using gradient descent')
|
||||
print(beta_Ridge)
|
||||
|
||||
# Gradient descent with Lasso
|
||||
beta_Lasso = np.random.randn(3,1)
|
||||
gradient = np.zeros(3)
|
||||
for iter in range(Niterations):
|
||||
gradients = 2.0/n*X.T @ (X @ beta_Lasso-y)+Lambda*np.sign(beta_Lasso)
|
||||
beta_Lasso -= eta*gradients
|
||||
print('Parameters for Lasso using gradient descent')
|
||||
print(beta_Lasso)
|
||||
|
||||
!ec
|
||||
|
||||
|
||||
!split
|
||||
===== But none of these can compete with Newton's method =====
|
||||
|
||||
Note that we here have introduced automatic differentiation
|
||||
!bc pycod
|
||||
# Using Newton's method
|
||||
from random import random, seed
|
||||
import numpy as np
|
||||
import autograd.numpy as np
|
||||
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+5*x*x
|
||||
|
||||
X = np.c_[np.ones((n,1)), x, x*x]
|
||||
XT_X = X.T @ X
|
||||
beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
|
||||
print("Own inversion")
|
||||
print(beta_linreg)
|
||||
# Hessian matrix
|
||||
H = (2.0/n)* XT_X
|
||||
# Note that here the Hessian does not depend on the parameters beta
|
||||
invH = np.linalg.pinv(H)
|
||||
beta = np.random.randn(3,1)
|
||||
Niterations = 5
|
||||
# define the gradient
|
||||
training_gradient = grad(CostOLS)
|
||||
|
||||
for iter in range(Niterations):
|
||||
gradients = training_gradient(beta)
|
||||
beta -= invH @ gradients
|
||||
print(iter,gradients[0],gradients[1])
|
||||
print("beta from own Newton code")
|
||||
print(beta)
|
||||
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Gradient descent and Logistic regression =====
|
||||
|
||||
Finally, we complete these examples by adding a simple code for
|
||||
Logistic regression. Note the more general approach with a class for
|
||||
the method. Here we use a so-called _AND_ gate for our data set.
|
||||
|
||||
!bc pycod
|
||||
import numpy as np
|
||||
class LogisticRegression:
|
||||
def __init__(self, learning_rate=0.01, num_iterations=1000):
|
||||
self.learning_rate = learning_rate
|
||||
self.num_iterations = num_iterations
|
||||
self.beta_logreg = None
|
||||
def sigmoid(self, z):
|
||||
return 1 / (1 + np.exp(-z))
|
||||
def GDfit(self, X, y):
|
||||
n_data, num_features = X.shape
|
||||
self.beta_logreg = np.zeros(num_features)
|
||||
for _ in range(self.num_iterations):
|
||||
linear_model = X @ self.beta_logreg
|
||||
y_predicted = self.sigmoid(linear_model)
|
||||
# Gradient calculation
|
||||
gradient = (X.T @ (y_predicted - y))/n_data
|
||||
# Update beta_logreg
|
||||
self.beta_logreg -= self.learning_rate*gradient
|
||||
def predict(self, X):
|
||||
linear_model = X @ self.beta_logreg
|
||||
y_predicted = self.sigmoid(linear_model)
|
||||
return [1 if i >= 0.5 else 0 for i in y_predicted]
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
# Sample data
|
||||
X = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
|
||||
y = np.array([0, 0, 0, 1]) # This is an AND gate
|
||||
model = LogisticRegression(learning_rate=0.01, num_iterations=1000)
|
||||
model.GDfit(X, y)
|
||||
predictions = model.predict(X)
|
||||
print("Predictions:", predictions)
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Overview video on Stochastic Gradient Descent =====
|
||||
|
||||
"What is Stochastic Gradient Descent":"https://www.youtube.com/watch?v=vMh0zPT0tLI&ab_channel=StatQuestwithJoshStarmer"
|
||||
There are several reasons for using stochastic gradient descent. Some of these are:
|
||||
|
||||
o Efficiency: Updates weights more frequently using a single or a small batch of samples, which speeds up convergence.
|
||||
o Hopefully avoid Local Minima
|
||||
o Memory Usage: Requires less memory compared to computing gradients for the entire dataset.
|
||||
|
||||
!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, 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 minibatch
|
||||
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. Such approaches are
|
||||
also called scaling. There are many such ways to "scale the learning
|
||||
rate":"https://towardsdatascience.com/gradient-descent-the-learning-rate-and-the-importance-of-feature-scaling-6c0b416596e1"
|
||||
and "discussions here":"https://www.jmlr.org/papers/volume23/20-1258/20-1258.pdf". See
|
||||
also
|
||||
URL:"https://towardsdatascience.com/learning-rate-schedules-and-adaptive-learning-rate-methods-for-deep-learning-2c8f433990d1"
|
||||
for a discussion of different scaling functions for the learning rate.
|
||||
|
||||
!split
|
||||
===== Time decay rate =====
|
||||
|
||||
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
|
||||
|
||||
|
||||
!split
|
||||
===== Code with a Number of Minibatches which varies =====
|
||||
|
||||
In the code here we vary the number of mini-batches.
|
||||
!bc pycode
|
||||
# Importing various packages
|
||||
from math import exp, sqrt
|
||||
from random import random, seed
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
n = 100
|
||||
x = 2*np.random.rand(n,1)
|
||||
y = 4+3*x+np.random.randn(n,1)
|
||||
|
||||
X = np.c_[np.ones((n,1)), x]
|
||||
XT_X = X.T @ X
|
||||
theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)
|
||||
print("Own inversion")
|
||||
print(theta_linreg)
|
||||
# Hessian matrix
|
||||
H = (2.0/n)* XT_X
|
||||
EigValues, EigVectors = np.linalg.eig(H)
|
||||
print(f"Eigenvalues of Hessian Matrix:{EigValues}")
|
||||
|
||||
theta = np.random.randn(2,1)
|
||||
eta = 1.0/np.max(EigValues)
|
||||
Niterations = 1000
|
||||
|
||||
|
||||
for iter in range(Niterations):
|
||||
gradients = 2.0/n*X.T @ ((X @ theta)-y)
|
||||
theta -= eta*gradients
|
||||
print("theta from own gd")
|
||||
print(theta)
|
||||
|
||||
xnew = np.array([[0],[2]])
|
||||
Xnew = np.c_[np.ones((2,1)), xnew]
|
||||
ypredict = Xnew.dot(theta)
|
||||
ypredict2 = Xnew.dot(theta_linreg)
|
||||
|
||||
n_epochs = 50
|
||||
M = 5 #size of each minibatch
|
||||
m = int(n/M) #number of minibatches
|
||||
t0, t1 = 5, 50
|
||||
|
||||
def learning_schedule(t):
|
||||
return t0/(t+t1)
|
||||
|
||||
theta = np.random.randn(2,1)
|
||||
|
||||
for epoch in range(n_epochs):
|
||||
# Can you figure out a better way of setting up the contributions to each batch?
|
||||
for i in range(m):
|
||||
random_index = 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.
|
||||
|
||||
|
||||
!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.
|
||||
|
||||
During the last decade 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":"https://arxiv.org/abs/1412.6980".
|
||||
|
||||
!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":"https://arxiv.org/abs/1412.6980" =====
|
||||
|
||||
A related algorithm is the ADAM optimizer. In
|
||||
"ADAM":"https://arxiv.org/abs/1412.6980", 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. The method isefficient when working with large
|
||||
problems involving lots data and/or parameters. It is a combination of the
|
||||
gradient descent with momentum algorithm and the RMSprop algorithm
|
||||
discussed above.
|
||||
|
||||
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
|
||||
===== Algorithms and codes for Adagrad, RMSprop and Adam =====
|
||||
|
||||
The algorithms we have implemented are well described in the text by "Goodfellow, Bengio and Courville, chapter 8":"https://www.deeplearningbook.org/contents/optimization.html".
|
||||
|
||||
The codes which implement these algorithms are discussed after our presentation of automatic differentiation.
|
||||
|
||||
|
||||
===== AdaGrad algorithm, taken from "Goodfellow et al":"https://www.deeplearningbook.org/contents/optimization.html" =====
|
||||
|
||||
FIGURE: [figures/adagrad.png, width=600 frac=0.8]
|
||||
|
||||
|
||||
===== RMSProp algorithm, taken from "Goodfellow et al":"https://www.deeplearningbook.org/contents/optimization.html" =====
|
||||
|
||||
FIGURE: [figures/rmsprop.png, width=600 frac=0.8]
|
||||
|
||||
|
||||
|
||||
===== ADAM algorithm, taken from "Goodfellow et al":"https://www.deeplearningbook.org/contents/optimization.html" =====
|
||||
|
||||
FIGURE: [figures/adam.png, width=600 frac=0.8]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
!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 =====
|
||||
|
||||
Reference in New Issue
Block a user