A gradient descent lab
The problem
Build a small optimizer in plain Python that minimises functions of one and two variables, checks its own derivatives numerically, and shows how the learning rate decides between fast convergence, slow progress and divergence.
Requirements
- A numerical derivative and gradient function using central differences
- A gradient descent loop that stops when the gradient is small or after a step limit
- Runs on at least one one-variable and one two-variable function with several learning rates
- A report of steps taken and final value for each run, including a divergent one
Technologies
- Python 3
- Central differences
- Partial derivatives and gradients
- Loops and functions
Step by step
- Write f, its exact gradient and a numerical gradient, and compare them at a few points.
- Write the gradient descent loop with a tolerance and a step limit.
- Run it with a small, a good and a too-large learning rate and record the results.
- Print a table of rate, steps and final value and explain each row in a sentence.
Expected result
A short program and table showing that the same method converges, crawls or diverges depending on the learning rate.
How it is evaluated
- The numerical gradient agrees with the exact one
- Every run stops, by tolerance or by the step limit
- The divergent case is detected rather than crashing
- The explanation matches the numbers
Ways to improve it
- Add momentum and compare the step counts
- Use a stretched bowl to show zigzagging
- Choose the learning rate automatically by trying several