Nag as optimiser in deep learning – day 36

Nesterov momentum uses the stored velocity to look ahead before evaluating a gradient. On a curved loss surface, the gradient at that predicted location can differ in magnitude or sign from the gradient at the current parameter.

Nesterov Accelerated Gradient (NAG): A Comprehensive Overview

Introduction to Nesterov Accelerated Gradient

Nesterov Accelerated Gradient (NAG), also known as Nesterov Momentum, is an advanced optimization technique introduced by Yurii Nesterov in the early 1980s. It is an enhancement of the traditional momentum-based optimization used in gradient descent, designed to accelerate the convergence rate of the optimization process, particularly in the context of deep learning and complex optimization problems.

How NAG Works

The core idea behind NAG is the introduction of a “look-ahead” step before calculating the gradient, which allows for a more accurate and responsive update of parameters. In traditional momentum methods, the gradient is computed at the current position of the parameters, which might lead to less efficient convergence if the trajectory is not perfectly aligned with the optimal path. NAG, however, calculates the gradient at a position slightly ahead, based on the accumulated momentum, thus allowing the algorithm to “correct” its course more effectively if it is heading towards a suboptimal direction.

The NAG update rule can be summarized as follows:

  1. Look-ahead Step: Compute a preliminary update based on the momentum.
  2. Gradient Calculation: Evaluate the gradient at this look-ahead position.
  3. Momentum Update: Adjust the momentum based on the newly computed gradient.
  4. Parameter Update: Finally, update the parameters using the adjusted momentum.

This approach reduces the chances of overshooting the minimum and enhances the stability of the convergence process.

Comparing NAG with Traditional Momentum

Momentum and NAG are both designed to accelerate gradient descent by smoothing the optimization path and helping the algorithm overcome obstacles such as local minima or flat regions. However, they differ in their approach and efficiency:

  • Momentum: In the traditional momentum method, the gradient is computed at the current parameter position. The update rule for momentum is:
vt=γvt−1+η∇J(θt)
θt+1=θt−vt

Here, vt is the velocity (momentum) term, γ is the momentum coefficient, η is the learning rate, and ∇J(θt) is the gradient at the current parameter position θt. The traditional momentum method can overshoot the minimum, especially if the learning rate or momentum term is too high, leading to instability.

  • Nesterov Accelerated Gradient: NAG modifies the momentum update by first predicting where the current momentum will take the parameters, and then calculating the gradient at this predicted location. The update rules for NAG are:
  • θ′=θt−γvt−1
    vt=γvt−1+η∇J(θ′)
    θt+1=θt−vt

    This look-ahead mechanism allows NAG to correct its path more effectively and reduces the risk of overshooting, leading to faster and more stable convergence.

    In essence, while both methods aim to accelerate convergence, NAG generally provides better stability and responsiveness due to its anticipatory step, making it more suitable for deep learning tasks where the loss surface can be highly non-convex with many flat regions and local minima.

    Mathematical Foundation of NAG

    The mathematical foundation of NAG lies in its ability to leverage the accumulated momentum more effectively by predicting where the momentum will take the parameters before applying the gradient update. This mechanism can be broken down into the following steps:

    1. Velocity Update:
    vt=γvt−1+η∇J(θt−γvt−1)

    Here, the velocity vt is updated based on the momentum from the previous step vt−1, the learning rate η, and the gradient at the look-ahead position θt−γvt−1.

  • Parameter Update:
  • θt+1=θt−vt

    The parameters θ are then updated by subtracting the velocity term vt, which has been adjusted using the look-ahead gradient.

    Proof of NAG’s Effectiveness: A Simple Example

    Let’s consider a simple quadratic objective function:

    J(θ)=12θ2

    The gradient of this function is:

    ∇J(θ)=θ

    Suppose the learning rate η=0.1 and momentum γ=0.9. We initialize θ0=1.0 and v0=0.

    Iteration 1

    • Traditional Momentum:
      • Compute the gradient: ∇J(θ0)=θ0=1.0
      • Update the velocity: v1=γv0+η∇J(θ0)=0.9×0+0.1×1.0=0.1
      • Update the parameters: θ1=θ0−v1=1.0−0.1=0.9
    • Nesterov Accelerated Gradient:
      • Look-ahead step: θ′=θ0−γv0=1.0 (since v0=0)
      • Compute the gradient at look-ahead position: ∇J(θ′)=θ′=1.0
      • Update the velocity: v1=γv0+η∇J(θ′)=0.9×0+0.1×1.0=0.1
      • Update the parameters: θ1=θ0−v1=1.0−0.1=0.9

    Iteration 2

    Traditional Momentum:


    • Compute the gradient: ∇J(θ1)=θ1=0.9

    • Update the velocity: v2=γv1+η∇J(θ1)=0.9×0.1+0.1×0.9=0.18

    • Update the parameters: θ2=θ1−v2=0.9−0.18=0.72


    • Nesterov Accelerated Gradient:

      • Look-ahead step: θ′=θ1−γv1=0.9−0.9×0.1=0.81

      • Compute the gradient at the look-ahead position: ∇J(θ′)=θ′=0.81

      • Update the velocity: v2=γv1+η∇J(θ′)=0.9×0.1+0.1×0.81=0.171

      • Update the parameters: θ2=θ1−v2=0.9−0.171=0.729



    • Iteration 3
    • Traditional Momentum:

      • Compute the gradient: ∇J(θ2)=θ2=0.72

      • Update the velocity: v3=γv2+η∇J(θ2)=0.9×0.18+0.1×0.72=0.234

      • Update the parameters: θ3=θ2−v3=0.72−0.234=0.486



    • Nesterov Accelerated Gradient:

      • Look-ahead step: θ′=θ2−γv2=0.729−0.9×0.171=0.576

      • Compute the gradient at the look-ahead position: ∇J(θ′)=θ′=0.576

      • Update the velocity: v3=γv2+η∇J(θ′)=0.9×0.171+0.1×0.576=0.2091

      • Update the parameters: θ3=θ2−v3=0.729−0.2091=0.5199



    As we can see from these iterations, Nesterov Accelerated Gradient (NAG) adjusts its updates by considering the future position of the parameters, leading to potentially faster convergence and a more accurate path towards the optimum. NAG takes into account where the momentum will take the parameters and adjusts the gradient accordingly, making it more robust, particularly in scenarios with complex loss landscapes.

    Practical Implementation Example in Code

    Here is an example of how NAG can be implemented in Python using TensorFlow:

    import tensorflow as tf
    
    # Define the model
    model = tf.keras.models.Sequential([
        tf.keras.layers.Dense(64, activation='relu', input_shape=(input_dim,)),
        tf.keras.layers.Dense(1)
    ])
    
    # Compile the model using Nesterov Accelerated Gradient (NAG)
    optimizer = tf.keras.optimizers.SGD(learning_rate=0.001, momentum=0.9, nesterov=True)
    model.compile(optimizer=optimizer, loss='mean_squared_error')
    
    # Train the model
    model.fit(X_train, y_train, epochs=100, batch_size=32, validation_data=(X_val, y_val))
    
    # Evaluate the model
    loss = model.evaluate(X_test, y_test)
    
    # Print test loss
    print(f'Test loss: {loss}')
    

    In this example, we use the TensorFlow library to build a simple neural network model. We configure the SGD optimizer with Nesterov Accelerated Gradient by setting the nesterov=True flag. This allows us to leverage the benefits of NAG, including faster convergence and improved stability during training.

    As You can see in our code example, There’s no direct term or function in TensorFlow or Keras that explicitly says “NAG is on” in the output or logs. However, enabling NAG is implicit when you set nesterov=True while using the SGD optimizer.If you want to confirm that Nesterov Accelerated Gradient (NAG) is being used in our example code, you can:


    1. Check the optimizer configuration after defining it:

      print(optimizer.get_config())

    This will output the configuration of the optimizer, including whether nesterov is set to True. Our Code Example output:

    {'name': 'SGD', 'learning_rate': 0.001, 'momentum': 0.9, 'nesterov': True, ...}

    This confirms that NAG is enabled. However, the model’s training logs won’t explicitly mention it unless you include a custom print statement for debugging. Conclusion

    Nesterov Accelerated Gradient (NAG) offers significant improvements over traditional momentum by incorporating a look-ahead mechanism, leading to faster and more stable convergence. Its mathematical foundation and practical implementations make it a powerful tool in the optimization toolbox, particularly useful for deep learning tasks where the optimization landscape is complex. Understanding the differences between NAG and traditional momentum, as well as the mathematics behind it, provides valuable insights into why NAG is often preferred in practice.

    Resources

    Nesterov Accelerated Gradient – Papers with Code

    Gradient Descent With Nesterov Momentum – Machine Learning Mastery

    Understanding Nesterov’s Momentum – DeepAI

    Accelerated Gradient Descent Lecture – University of Wisconsin-Madison

    Yurii Nesterov – WLA Prize

     

    Calculate a look-ahead step

    Define a positive stored velocity as a displacement to subtract. First subtract the momentum contribution to predict where the next iterate would go. Evaluate the gradient there, add the gradient contribution to the velocity, and subtract the resulting velocity from the original iterate.

    qt=θt−γvt−1
    vt=γvt−1+η∇J(qt),θt+1=θt−vt

    For a quadratic with unit curvature, start a step at 0.2 with previous velocity 0.4, momentum 0.9, and learning rate 0.1. The predicted point is −0.16, whose gradient is −0.16. Nesterov gives a velocity of 0.344 and lands at −0.144. Heavy-ball uses the current gradient 0.2, gives a velocity of 0.38, and lands at −0.18.

    Calculate a look-ahead stepPredictFollow velocityMeasure slopeAt predicted pointApply updateFrom original point
    If the projected point crosses the minimum, its gradient can oppose the accumulated velocity.

    Compare implementations and outcomes

    PyTorch SGD and Keras 3 SGD expose Nesterov options and write the update in terms of the gradient at the optimizer’s current parameter representation. Compare their equations and initial buffer conventions before expecting step-for-step reproduction of the look-ahead pseudocode.

    Compare plain momentum and Nesterov at the same number of optimizer steps. Track both the objective and displacement size on a controlled quadratic, then tune both methods independently on the target validation split. A larger step with lower objective at one iteration can still give a worse trajectory later.

    References

    Practice and FAQs

    What happens on the first step if the velocity starts at zero?

    In the explicit look-ahead equations, the predicted point equals the current point. The first parameter update then matches the corresponding gradient descent step.

    Does Nesterov need two gradients per step?

    The explicit formulation evaluates one gradient at the look-ahead location. The displacement used to find that location comes from the stored velocity.

    Why did the look-ahead gradient point back toward the minimum in the worked example?

    The predicted parameter was negative on a unit-curvature quadratic. Its negative slope reduced a positive velocity that would otherwise have moved the parameter farther left.

    Leave a reply

    Your email address will not be published. Required fields are marked *

    You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
    Open on the App Store