Machine Learning

Example: gradient descent, from intuition to implementation

A worked example connecting the geometry of optimization to a small, reproducible implementation of gradient descent.

Optimization often begins with a simple question: which direction makes an error smaller? Gradient descent turns that local question into a repeatable procedure.

Start with a landscape

For a differentiable objective L(θ)L(\theta), the gradient points in the direction of steepest local increase in Euclidean space. A small step in the opposite direction is a useful first approximation to improvement.

θt+1=θt−η∇L(θt)\theta_{t+1} = \theta_t - \eta \nabla L(\theta_t)

Here η>0\eta > 0 is the learning rate. Choosing it is part of the algorithm, not an incidental implementation detail.

Nested elliptical contours converge on a minimum, with a dotted path descending toward the center.
An illustrative loss landscape; contours represent equal objective values.

A minimal implementation

For L(x)=x2L(x)=x^2, the derivative is 2x2x. Start at x=4x=4 and take ten steps:

def minimize(x: float, rate: float, steps: int) -> float:
    for _ in range(steps):
        gradient = 2 * x
        x -= rate * gradient
    return x

print(minimize(x=4.0, rate=0.2, steps=10))
# Approximately 0.0242

This is intentionally small enough to inspect by hand. Every iteration multiplies xx by 1−2η1-2\eta. Convergence therefore requires ∣1−2η∣<1|1-2\eta|<1, or 0<η<10<\eta<1.

Explore the learning rate

The control below computes one step for the same quadratic. At the largest rate it oscillates rather than improving.

One step from x = 4: x = 2.40
Learning rateFirst stepBehavior for this quadratic
0.13.2Gradual convergence
0.50.0Reaches the minimum
1.0-4.0Oscillation

Know the assumptions

A useful algorithm can still fail when its assumptions change. Nonconvex losses have saddle points; noisy gradients change the trajectory; poorly scaled coordinates slow progress.

Measure the objective as well as the parameter update. A moving parameter is not evidence of a better model.

Further reading

Boyd and Vandenberghe’s Convex Optimization develops the mathematical background.1 For an infrastructure perspective, read the static publishing example.

Footnotes

  1. Stephen Boyd and Lieven Vandenberghe, Convex Optimization, Cambridge University Press, 2004. See the freely available book on the authors’ website. ↩

NumPy source repository ↗

Discussion

Comments are not enabled yet. Thank you for reading.