Skip to content

About

Gradient descent, SGD, Momentum, NAG, AdaGrad, RMSProp, Adam, Newton's method and BFGS written from scratch in NumPy, and compared on linear regression and test functions.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

Gradient descent from scratch

Python NumPy License

Libraries like PyTorch hide the optimiser behind one line of code. I wanted to see what actually happens to the parameters on every step, so I wrote the optimisers myself in NumPy and watched them train a linear regression model.

I built this during the ITI Data Science diploma, as a series of practical exercises.

What's inside

In the order I wrote them:

Notebook What it covers
Gradient Descent for Linear Regression.ipynb Plain gradient descent, step by step: predict, compute the MSE, compute the gradient, update. First on one variable (RegData.csv), then vectorised for several (MultiVarLR.csv).
Batch, Stochastic and Mini-Batch GD.ipynb The same model trained three ways: on all the data per step, one point per step, and small batches of 5, 10 and 20.
Momentum and NAG.ipynb Batch gradient descent, then Momentum and Nesterov accelerated gradient (NAG), on a single-variable regression. I tried momentum values from 0.5 to 0.9 to see how it changes the path to the minimum.
Adagrad, RMSProp, and Adam.ipynb The three adaptive learning-rate methods, each built on the previous one. I compared learning rates of 0.05, 0.005 and 0.0005, and played with Adam's beta1 and beta2.
Newton Method and BFGS.ipynb Second-order methods: gradient descent vs Newton's method on one- and two-variable functions, then BFGS on the same functions.
Comparative Analysis between BFGS & Adam.ipynb A vectorised Adam and a BFGS optimiser, both training a multivariable regression on the same data, with the same learning rate and stopping tolerance.

Most notebooks fit a line to points generated from y = ax + b. The first and last ones also use MultiVarLR.csv, a small dataset with 24 rows, three features and one target.

The main result: BFGS vs Adam

Both optimisers used a learning rate of 0.5 and a tolerance of 1e-4. They stop when the loss change or the gradient norm drops below the tolerance.

Optimiser Iterations to converge R²
BFGS 43 (the loop counter prints 42) 0.990
Adam 388 0.989

They end up with nearly the same fit, but BFGS gets there about nine times faster. That makes sense. BFGS builds an estimate of the curvature (the inverse Hessian) as it goes, so it takes better-scaled steps. Adam only rescales each parameter using running averages of the gradient.

Newton's method, and a function with no minimum

Function Gradient descent Newton BFGS
x² − 15x + 1 321 steps, stops at x = 7.55 1 step, x = 7.5 exactly –
x² + y² 46 steps (learning rate 0.1) 1 step 1 step
x² + xy + y² 16 steps (learning rate 0.5) 1 step 1 step
x²y 79 steps, stops at (0, 6.85) 9 steps, stops near (0, 0) 13 steps, stops near (0, 0)

Newton needs one step on the first three because they're quadratics, and its update is exact for a quadratic.

The last one is the interesting one. x²y has no minimum at all: make y negative and it goes down forever. Every optimiser still reported "found solution", because all they check is whether the gradient is close to zero. Gradient descent stopped on the line x = 0, where the function is flat. Newton and BFGS went to the origin, which isn't a minimum either: step towards negative y and the value drops. A small gradient tells you you're at a stationary point, not that you've found the bottom.

Batch vs stochastic vs mini-batch

All three variants reached R² ≈ 0.998 on the same 50 points. Stochastic GD stopped after about 4 passes over the data, and mini-batches of 5, 10 and 20 after about 11, 18 and 34, against 77 for full-batch. Smaller batches make many more updates per pass, so they need fewer passes, but each update only sees part of the data.

Caveats

  • This is one small dataset with four parameters. I wouldn't claim the BFGS vs Adam ratio holds elsewhere.
  • I compared iterations, not time. A BFGS iteration costs more, because it updates a matrix every step. With four parameters this barely matters. With millions it would be a problem, and it's why Adam is the usual choice for neural networks.
  • A good R² doesn't mean the right parameters. In the batch notebook the data comes from y = -2x + 1 with no noise, yet the intercept stops around -0.13 while R² is already 0.998. The stopping rule ends training before the intercept, which moves slowly, gets anywhere near 1.
  • The notebooks print every iteration, so the saved outputs are long. Jupyter truncates them.

How to run

pip install numpy pandas matplotlib scikit-learn sympy jupyter
jupyter notebook

Open any notebook and run the cells in order. The BFGS vs Adam notebook reads the data from /content/MultiVarLR.csv, which is the Google Colab path. If you run it locally, change that line to MultiVarLR.csv.

What I'd like to do next

Try these optimisers on a real non-convex loss, such as a small neural network, and plot their paths over the loss surface.

About

Gradient descent, SGD, Momentum, NAG, AdaGrad, RMSProp, Adam, Newton's method and BFGS written from scratch in NumPy, and compared on linear regression and test functions.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages