smartyfy.mrindigi.com

AI & Machine Learning Master Course — 018. Optimization with gradient descent

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 018: Optimization with gradient descent

Prerequisite: Lesson 017. Learning outcome: Implement a small gradient-descent optimizer, explain its update rule, and diagnose slow progress, oscillation, and divergence without confusing training improvement with generalization.

1. Turn a derivative into an update

A gradient describes local sensitivity. An optimizer uses that information to choose parameter changes. The basic gradient-descent update is: new parameters equal old parameters minus a positive learning rate times the gradient evaluated at the old parameters.

The minus sign matters because the gradient points toward greatest first-order increase in ordinary Euclidean coordinates. The learning rate controls the step size. It is a configuration choice, not a quantity automatically equal to the loss or gradient magnitude.

For a parameter vector, compute the complete gradient at the current vector before updating its entries together. Changing one parameter and then using that altered value to calculate another component implements a different procedure unless that behavior is explicitly intended.

The Google gradient-descent lesson introduces iterative loss reduction using gradients. We will examine one objective closely enough to explain exactly when the update works.

2. Work through the first steps

Choose J(w) = (w − 3) squared. Its minimum is at w = 3, where the loss is zero. The derivative is 2(w − 3). Start at w = 0 and use learning rate 0.1.

The first derivative is −6, so the update is 0 − 0.1 × (−6) = 0.6. The new loss is (0.6 − 3) squared = 5.76, down from 9. The next derivative is −4.8, producing w = 1.08 and loss 3.6864.

A third update gives w = 1.464. Each step moves closer to 3, but the amount shrinks because the derivative shrinks. This is a simple example of convergence: the sequence approaches a solution as iteration continues.

These numbers describe a known mathematical function, so we can verify the behavior analytically. Real model objectives may be more complicated, making logged trajectories and checks especially valuable.

3. Derive the learning-rate condition for this example

Let the current error be e = w − 3. After one update, new error equals e − 2αe, or (1 − 2α)e, where α is the learning rate. The error shrinks in magnitude when the absolute value of 1 − 2α is less than one.

For this particular quadratic, that condition is 0 < α < 1. With α = 0.1, the error multiplies by 0.8. With α = 0.75, it multiplies by −0.5, so the parameter crosses the optimum while getting closer each time.

At α = 1, the error changes sign without shrinking. Starting at zero, the parameter alternates between 0 and 6, with loss 9 at both points. At α = 1.1, the multiplier is −1.2, so the error grows while alternating sides.

The interval above is not a universal safe learning-rate range. If the loss is multiplied by 100, its gradient and curvature change, and the same learning rate can behave very differently. The next lesson connects this effect to curvature and numerical conditioning.

A logarithmic loss plot compares iterations0 through12 for rates0.1,0.75,1.0,1.1. The first two decline;0.75 crosses the optimum while error magnitude halves. Rate1 stays at loss9, while1.1 grows. Exact formula9(1−2alpha)^(2k) generates every point.
A small enough rate can converge with or without crossing the minimum. Larger rates can oscillate without progress or diverge; the safe interval depends on the objective’s curvature. Open full-size diagram

4. Implement a bounded optimizer

This standard-library CPU example records the parameter, loss, and gradient before each update. It runs a fixed number of steps so the different trajectories remain directly comparable. It was checked with Python 3.12.14 and needs no external service.

import math

def objective(w):
    return (w - 3.0) ** 2

def optimize(rate, steps=12, initial=0.0):
    w = float(initial)
    history = []
    for step in range(steps):
        gradient = 2.0 * (w - 3.0)
        value = objective(w)
        if not all(map(math.isfinite, [w, gradient, value])):
            raise ArithmeticError("Non-finite optimizer state")
        history.append((step, w, value, gradient))
        w = w - rate * gradient
    return w, history

for rate in [0.1, 0.75, 1.0, 1.1]:
    final_w, history = optimize(rate)
    print(rate, "final w:", round(final_w, 6),
          "final loss:", round(objective(final_w), 6))
    if rate in [0.1, 0.75]:
        assert objective(final_w) < objective(0.0)
    if rate == 1.0:
        assert final_w == 0.0
    if rate == 1.1:
        assert objective(final_w) > objective(0.0)

_, first_steps = optimize(0.1, steps=3)
assert math.isclose(first_steps[1][1], 0.6)
assert math.isclose(first_steps[2][1], 1.08)

The two rates inside the derived interval reduce the objective. Rate 1.0 returns to the starting point after the even number of steps. Rate 1.1 increases the loss. Inspecting the logged history distinguishes useful oscillation from a failure to shrink.

Do not hide a divergent trajectory by deleting its final rows or reporting only the best intermediate point without explanation. Record the failed configuration and investigate its cause.

5. Choose stopping checks thoughtfully

A fixed iteration budget is easy to reproduce but may stop before convergence. A small gradient norm can indicate a stationary region, although it does not prove a global minimum. A tiny change in loss can indicate progress has slowed, but floating-point limits or a poor parameter scale can also cause that symptom.

Use a combination of a maximum budget, finite-value checks, and a justified convergence criterion. For educational examples, compare with a known solution when available. Record why the optimizer stopped instead of treating every return from a function as success.

In supervised learning, validation performance can guide stopping when continued fitting worsens held-out development behavior. Final test data must not become a repeatedly consulted stopping signal. Optimization and model selection have different evidence boundaries.

6. Separate optimization from the learning objective

Our optimizer knows only the objective it receives. If the objective is poorly chosen, accurately minimizing it can still produce an unhelpful system. If a model memorizes training examples, training loss may fall while future prediction quality does not improve.

For a training dataset, the objective often averages losses over examples. Full-batch gradient descent uses that complete training objective for each update. Mini-batch methods use subsets, introducing variation in the update direction. They can be useful computationally, but their trajectories need not decrease at every step.

Do not transfer the monotonic behavior of our smooth one-parameter demonstration to every optimizer or neural-network training run. Check the actual objective, sampling procedure, and evaluation setting before interpreting a curve.

Practice: four questions with worked answers

1. For J(w) = (w − 3) squared, start at w = 5 with learning rate 0.1. Find the next parameter.

Answer: The gradient is 2 × (5 − 3) = 4. Subtract 0.1 × 4 from 5 to obtain 4.6. The parameter moves toward the optimum.

2. What happens with learning rate 0.5 on this objective?

Answer: The error multiplier is 1 − 2 × 0.5 = 0. One update reaches w = 3 from any finite starting value in exact arithmetic. This special result depends on this objective.

3. Is alternating around the optimum always failure?

Answer: No. With learning rate 0.75, the error changes sign but halves in magnitude. Check whether the distance and objective shrink, rather than judging only the direction changes.

4. Training loss falls while validation loss rises. Should you keep training solely because optimization is working?

Answer: No. The intended goal includes generalization. Investigate overfitting and use the predefined validation-based selection or stopping procedure without consulting the final test repeatedly.

Knowledge check: five explained MCQs

1. Basic gradient descent updates parameters by: A. Subtracting learning rate times gradient. B. Adding learning rate times gradient. C. Replacing every value with the loss.

Correct: A. The update follows a locally descending direction with a controlled step size.

2. The gradient in one simultaneous update is evaluated at: A. The final test answers. B. The current parameter vector. C. A vector partly changed by earlier component updates.

Correct: B. All components belong to the same point before the vector update.

3. A larger learning rate always converges faster: A. True. B. False. C. True whenever the loss is convex.

Correct: B. Excessive steps can oscillate without improvement or diverge.

4. A small gradient norm establishes: A. Universal accuracy. B. A potentially stationary region requiring interpretation. C. A guaranteed global minimum for every objective.

Correct: B. Objective geometry and numerical behavior determine the stronger conclusion.

5. A decreasing training objective is: A. Evidence of optimization progress on that objective. B. Proof of future performance. C. Permission to skip a baseline.

Correct: A. Generalization and practical usefulness need separate evaluation.

Common pitfalls and summary

Watch the update sign, evaluation point, learning rate, finite values, and stopping reason. A simple recurrence explains why gradient descent can improve, oscillate, or diverge. Optimization is a tool for fitting an objective; it does not establish that the objective or resulting model is useful.