r/MachineLearning • • Jul 08 '24

Research [R] Experimenting with Gradient Descent. Why not Nelder-Mead? Long.

There are a lot of videos and web pages about GD. However, almost all of the examples are too simple. I dug up some data from 2005 that has only five parameters to determine yet GD took fooorrreeeevvveeer. It seemed like the GD was always bouncing of obstructions.  It was also very dependent on the step size. Too much guessing on the step size is required.  I wondered what could make this so difficult because other methods like Nelder-Mead could find the minimum in a few seconds. To answer my questions, I printed out the MSE for each iteration and the five parameters or MSE and the change in the five parameters.

There is no formula to differentiate when using real data.  I had to estimate the derivative for each parameter by taking small steps in each direction and dividing the by the difference 2 times the increment. To get a central difference slope I had to take a small step in the positive and negative direction for each parameter and divide by the two times the step. The derivative could be noisy with real data. Each small step required evaluating the cost function so 10 evaluations were necessary to calculate the gradient.  This was time consuming.  What I found is that unlike YouTube and other common examples, the "terrain" was not like a bowl but rather like the Grand Canyon with all sorts of twists and turns. This meant I could not use large steps because the GD would often run into the "canyon walls" in 5 dimensions. I then tried many other enhanced versions of GD and none of them worked very well although some would get close in an hour or so. GD-Adam GD-RMSprop GD-delta GD-AdaGrad did not do very well. However, I did find a new add on code that makes all of them and especially the simple GD work MUCH better. The trick is to take a step. Evaluate it and if it is better then take another step in the same direction until the MSE is no longer getting better then repeat the loop to get a new gradient. The advantage if this is the there is less time wasted calculating gradients that just "slam" against the "walls". Also, the step size can be a little smaller to navigate the parts of the "terrain" that are twisty but being able to take multiple steps in a direction when a good direction is found is like taking a much bigger step.

Intuitively it works like this. The starting point is some place in the canyon with a stream. The stream is the current low point. However, it twists and turns so any step will hit the banks of the stream and maybe the canyon walls. It is best not to follow the stream exactly because of the many twists and turns. It would be best to "fly above the stream" between the "canyon walls" in one direction as far as possible. This avoids a lot of computing gradients because if there is a lot of data then a lot of gradients must be computed and that can be very time consuming.

Now all of this makes no difference if you have nice bowl like terrain. Any of the methods you see on YouTube or websites will work but I have never seen one work with real data and chances are the terrain will not be a nice bowl-like structure. Also, finding the derivatives with 10 of thousands of points is expensive time wise.

This is why I wonder why Nelder-Mead isn’t used except for the fact that it would use a lot of memory if it were to be efficient, but memory is cheap.

I have watched many YouTube videos about different forms of gradient descent. I am convinced that most teach what they have been taught and haven't really delt with real data.

Next is to find some real training data for identifying characters in an 8x8 grid but even 16x16 dot matrix would be good.  I know I am re-creating the wheel, but I want to try my new add on code and Nelder-Mead for minimizing cost functions

GD #gradient-descent, #Nelder-Mead, #Adam #AdaGrad, #Delta, #RMSprop

3 Upvotes

24 comments sorted by

11

u/alexsht1 Jul 08 '24

I think there are three main reasons why GD is often preferred in the ML commuinity:

  1. Lack of online / stochastic variants of Nedler-Mead, with convergence proof or empirical analysis, that allow making progress without going through the entire data-set in each iteration, i.e. mini-batch SGD.

  2. Theory of convergence of gradient descent - the faster theoretical rates achievable by various acceleration techniques, such as momentum or Adam, empower the belief that these methods are faster to work with. I don't know if anyone actually put this to a test.

  3. Software engineering - automatic differentiation is a 'solved problem'. We can compute gradients for almost anything, so (stochastic) GD is extremely easy to use.

1

u/pnachtwey Jul 09 '24

"Lack of online / stochastic variants of Nedler-Mead,"

1, Lack of means no one has tried? I need to try Nelder Mead in a batch like system where I an trying to do number recognition just for starters.

2 GD-Adam fails miserably with my test data. Anything with a momentum just hits one of the "canyon walls" and bonce back and forth between them unless it gets lucky and finds the narrow path.

3. Yes, GD is easy. I am using numerical differentiation. I will look up automatic differentiation to see if it will add to my bag of tricks. Thanks for the hit.

Still GD is slow. I will check into the automatic differentiation to see if that speeds things up.

The point of my original post is that none of the GD methods work well if the path to the minimum is extremely narrow.

More research required.

-18

u/pnachtwey Jul 08 '24

Agreed. GD is easy to implement and easy to use but it doesn't work that well. There is too much fiddling around with "hyper parameters". It also depends on computing a gradient which Nelder-Mead does not. I agree that N-M is a more complicated algorithm and possibly a memory hog.

N-M can be applied to a subset of the parameter just like GD. Why not? This is what I want to try but I will first try applying N-M to all parameters. I know that N-M gets bogged down if there are too many parameters but GD is so poor it is a matter of which is "less bad"

N-M finds the minimum much faster than GD in my test data. It is about a factor of 50-100 times faster.

Again, teachers teach what they have been taught but I have spent a lot of time analyzing my test data. It really is like the Grand Canyon and not a simple x^2+Y^2 that professors use. They should at least show how to minimized the Rosenbrock formula.

In a way this isn't fair. I am very familiar with N-M, Powel, BFGS, L-BFGS, CG and others. I know where they are superior and where they fail. Just about anything will work well when minimizing some form of f(x,y)=x^2+y^2. However, that is not reality.

Tell me, how does one compute the gradient if there are 100 variables to optimize? What if there are more?

23

u/alexsht1 Jul 08 '24

Nobody computes gradients these days. Software computes them for us. When training models with PyTorch, TensorFlow or Jax, there is an automatic differentiation mechanism that given code to compute a function, constructs a computational algorithm to compute its gradient. It is very efficient, and plenty of research has been done on automatic differentiation prior to that. See this tutorial from PyTorch:

https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html

So we don't care how many variables are there. Gradients are always available.

10

u/DrXaos Jul 08 '24 edited Jul 08 '24

Stochastic gradient descent is not taking a descent step on a fraction of parameters, it's taking a step over all parameters but evaluated on a fraction of the data. The point in machine learning is that SGD and variants (Adam is most commonly used to adapt learning rates per parameter) let one train with enormous dataset sizes on large parameter spaces and little else works so far in that regime. It's the large models with even larger datasets which are behind the ability of ML systems to approximate and solve some kinds of AI problems.

So you'd have to have a N-M which works on stochastically selected subsets, but generally ignoring the gradients which can be computed at low cost is going to hurt performance. Even knowing just the sign of the gradient is important.

10

u/trajo123 Jul 08 '24 edited Jul 08 '24

Tell me, how does one compute the gradient if there are 100 variables to optimize? What if there are more?

Lol. You do realise that real-world models have 107 - 1012 parameters (yes, a trillion in case of LLMs)

Gradients are computed symbolically through automatic diffentiation of the computational graph defined by the model. They are not computer numerically like in your examples.

In other words, the exact gradient is computed (no approximation) directly (using formulas, no numerical methods).

5

u/Calm_Bit_throwaway Jul 08 '24 edited Jul 08 '24

Why wouldn't you use gradient information when it's so cheap and easy to compute, especially when the loss landscape in many deep learning applications is relatively smooth? It depends on your specific application but GD/SGD is used easily in real world data with hundreds of millions of parameters for highly non trivial losses.

I'm not sure why you're approximating the gradient numerically either. It can be done for a wide class of deep learning models with automatic differentiation and back propagation. This has memory and compute complexity linear in the number of parameters so should scale up easily to millions of parameters.

3

u/trajo123 Jul 08 '24

There is no formula to differentiate when using real data.

What exactly do you mean by this? Do you mean that you have no model at all (so only data), or that your model is a black box or non-differentiable?

I had to estimate the derivative for each parameter by taking small steps in each direction and dividing the by the difference 2 times the increment.

Parameter of what? ...so you do have a model with parameters then, is the model differentiable or not?

I then tried many other enhanced versions of GD and none of them worked very well although some would get close in an hour or so.

I guess you either don't know about automatic differentiation or your model is not differentiable since you are estimating the gradient numerically.

I think deepening your understanding of some critical aspects of how modern deep learning models are optimized (and why), may help clear up your confusion related to why SGD variants are the best option for deep learning models:

  • gradient based / gradient free optimisation: big topics, look it up

  • automatic differentiation. Very complex model can be implemented in frameworks supporting automatic differentiation, especially if your inputs are continous, meaning that exact gradients can be obtained extremely efficiently.

  • making models easier to optimize: for a long time, training deep networks was not practically possible, a few insights made this problem go away: ** avoiding exploding / vanishing activations and gradients by principled parameter initialisation and using normalisation (batch-norm, layer-norm, etc) ** avoiding saturating non-linearities (e.g. avoiding sigmoid / tanh, using ReLU, Silu, etc) ** use residual connection: so that in the computational graph of the model, all parameters are a couple of steps away from the loss function, rather than having very long computational chains

To me it sounds like your problem is very different from deep learning. Your model has few parameters, but the loss landscape is extremely jagged / non-smooth which means that the gradients are not very informative in terms of pointing towards the optimum, so in general quite many gradient evaluations are needed. The best way to solve this problem is to try to make your model automatically differentiable (look into Pytorch, or some matlab automatic differentiation package if that is your cup of tea). If you can't make it automatically differentiable, then maybe you should just opt for some non-gradient based optimisation algorithms.

0

u/pnachtwey Jul 09 '24

I must differentiate the cost function after taking small steps, positive and negative, for each parameter. This takes 10 evaluations of the cost function. I could just use a forward or backwards difference, but the central difference seems to work better. There is no formula like f(x,y)=x^2+y^2 to differentiate. This is where the YouTube videos are misleading.

The parameters are what needs to be optimized. In my case it is a gain, two time constants, ambient temperature and a dead time. It isn't for training a neural net. I am doing system identification, but the gradient descent should still find the parameters that minimize the cost function.

How do you know what the "terrain" is like for training character recognition? You don't. Where is the formula to differentiate to get the gradient? You don't have one.

Yes, it is different from deep learning, but the GD algorithms are the same and the goal is still to find the parameters that minimize the cost function. In NN you have weights and biases. The YouTube videos assume the "terrain" is relatively smooth without a lot of narrow turns. My model is a differential equation that is integrated using Runge-Kutta and recording the MSE between the temperature set point and the actual temperature. Nelder-Mead and Levenberg- Marquardt solve this in seconds whereas the fastest version of GD takes about 5-6 minutes. Another issue is that I am looking for a true minimum, not a good enough like GD seems to provide.

This is why I am looking for some training data for recognizing characters. The problem is that if the characters are 8x8 pixels and there are 10 digits to recognize there is too much to look at for each iteration.

Also, my modified GD with a line search is 66 times faster than the GD alone when using the same step size. That is significant. It is faster than the other versions of GD that I have tried.

2

u/trajo123 Jul 09 '24

I must differentiate the cost function after taking small steps, positive and negative, for each parameter.

This makes absolutely no sense. What is your model? ...The thing that makes the prediction which you plug into the cost function.

1

u/pnachtwey Jul 09 '24

Sure it does, My model or differential equation is the _dy2dt equation it has a gain k, two time constants ( _t0,t_t1), ambient temperature _c and dead time _dt. The control to the system is _u. The time, control and actual temperature are recorded. The parameters are changed so the mea squared error between the recorded temperature and the estimated temperature form the model.

def difeq(y, t, p):

""" generate estimated SOPDT solution

y[0] = process value

y[1] = rate of change of the process value"""

_k = p[gain] # open loop extend gain

_t0 = p[t0]

_t1 = p[t1]

_c = p[off] # output offset or bias

_dt = p[dead]

_u = float(control_interp(max(t-_dt,0))) # compensate for dead time

_dy2dt = (-(_t0+_t1)*y[1]-y[0]+_k*_u+_c)/(_t0*_t1)

return np.array([y[1], _dy2dt]) # return PV' and PV''

I know you consider this to be one batch and not the result of multiple batches.

Nelder-Mead and scipy.optimize.least_squares solves this in seconds. GD-Adam just flails and fails.

Normal GD solves in 5891 seconds. The line search trick I use solve in 88 seconds. The point is that my line search modification is MUCH faster in ?rough terrain".

Can't this website do a better job of displaying code?

3

u/trajo123 Jul 09 '24

From your code it's not clear what the model is and how the output of the model is used in the cost function. Also, what are t0 and t1, global variables?

The parameters are changed so the mea squared error between the recorded temperature and the estimated temperature form the model.

Where is the estimated temperature calculated? What do you mean by "form the model"?

I would expect something like:

a, b, c = ... # some initial parameters of the model
def model(inp1, inp2, inp3):
   est_temp = (a + inp1 + b * inp2) / c^inp3  
   # ...or any other function of the inputs and model parameters
   return est_temp
        
def cost_func(est_temp, recorded_temp):
   return (predicted - actual)^2  # or any other cost function

In any case, your code looks like it would work with automatic differentiation. If you would implemented using pytorch tensors you could just do:

optimizer = optim.SGD([a, b, c], lr=0.0001)

for step in range(n_training_steps):  
   est_temp = model(....)  
   loss = cost_func(est_temp, recorded_temp)  
   loss.backward() # this automatically calculates the gradient - aka the partial derivatives of the loss with respect to the model parameter (a, b, c in this case)  
   optim.step()

You could probably ask an LLM to write the code for you. You can chose between multiple optimizers starting with SDG then going to Adam. You may want to try out the Nesterov flag which might help with highly curved loss landscapes.

Anyway, I explained in my previous comment how your suggestion of using Nelder-Mead is completely out of the question for deep learning because the number of parameters is usually in the order of millions up to a trillion. And Nelder-Mead is used when you don't have the gradient, but in deep learning models you do because of automatic differentiation.

edit: formatting

1

u/pnachtwey Jul 12 '24

You misunderstand. There is no model like

def model(inp1, inp2, inp3):
   est_temp = (a + inp1 + b * inp2) / c^inp3  
   # ...or any other function of the inputs and model parameters
   return est_tempdef model(inp1, inp2, inp3):
   est_temp = (a + inp1 + b * inp2) / c^inp3  
   # ...or any other function of the inputs and model parameters
   return est_temp

Where the estimate temperature is calculated off of a few inputs as in your example. There is 1200 recorded readings of time, control output and the actual temperature. The state at time t is dependent on the states and the control signals before. You model doesn't take this into account. In my simulation the estimated temperatures at the end are dependent of all the data leading up to the end. The past affects the future. There is a dead time. The dead time is the time if takes for the system to respond to an input. This is important in control and in modeling the economy.

Estimating SOPDT parameters

You can see the green line is the control signal to the heater. The cyan or light blue line is the recorded actual temperature. My algorithm computes the 5 parameters so that the dydt, the change in temperature with respect to time, formula will estimate a response, the red line, that matches the actual recorded temperature. You can see my estimation is quite good. I can then use the 5 parameters to calculate the PID gain to control the temperature ( not shown ).

This is call system identification which is part of auto tuning.

2

u/trajo123 Jul 12 '24

Ok, so you have no differentiable model, whereas in deep learning there always is. This is the answer to your initial answer "Why not Nelder-Mead?". Makes sense?

1

u/[deleted] Jul 12 '24 edited Mar 28 '25

[removed] — view removed comment

2

u/trajo123 Jul 12 '24

You can use gradient descent with numerically estimated gradients.

38

u/cofapie Jul 08 '24 edited Jul 08 '24

The loss landscape is usually nice for gradient descent in the double descent regime (parameters>>data points), especially with residual connections.

I'm not convinced that you're doing deep learning correctly. If your loss function is differentiable, your network is differentiable, then you should not be estimating derivatives.

The most real data is what is actually being done with deep learning - such as NLP or CV. No one is telling you to use neural networks for low dimensional tabular data.

Moreover, GPU memory is very much not cheap and a huge limiting factor for training.

5

u/Investing-eye Jul 08 '24

I'm not sure on the exact details of your optimisation, but it doesn't sound alike a neural network. We use gradient descent in NNs as we know the gradient of the loss function for free by design. As such, the model requires 0 evaluations to to calculate the gradient. Furthermore, each optimisation step modifies every parameter - this is particularly important when considering NNs have many parameters.

NM doesn't require gradients, so for NNs we are essentially throwing away this information. There's no need to use the NM heuristics if we already know which way downhill is. I think the real limitation is that each iteration modifies only a single point on an N+1 simplex per iteration. This means for many parameter models, it will be expensive and slow to modify every N+1 points.

Finally you node GD requires hyper-parameteres. It requires only the learning rate. NM also requires a hyper-parameter corresponding to the initial size of the symplex. Theses hyperparamters play similar roles in both algorithms, too small and we only perform a local search, too big and we may jump over suitable minima.

5

u/serge_cell Jul 08 '24

Nelder-Mead is effectively numerical estimation of gradient and as such would have problems in noisy environment which DNN is. What people keep forgetting about is vanilla SGD which often outperform and/or more stable then other methods if proper model-specific step heuristics is used.

3

u/M4mb0 Jul 08 '24

GD is the best thing we have in high dimensional setting. I wouldn't doubt that it is ineffective on some specific examples with only 5 variables. 

Moreover it is almost never plain GD, but usually SGD (which has useful regularizing effects) or GD+momentum

2

u/slashdave Jul 08 '24

A couple things to unpack here.

First, there is no such thing as a universal minimization algorithm. Most of the algorithms you are studying rely on a quadratic approximation of a minimum. For well behaved problems, only the close vicinity of the minimum behaves this well, and you do not start there.

Second, deep learning relies on stochastic gradient descent. There is a good reason for this (besides questions of performance). The idea is to use an approximate method to iteratively travel to the minimum. Since you start no where near any minimum (the solution is singular by design, so there are many, many duplicate minima), approximate methods work far better.

2

u/KomisarRus Jul 08 '24

Because you have gradient for free from the linear algebra of neural networks. Amoeba optimization compensates for the general lack of gradient with sampling a few points of interest and then makes steps on the direction it seems like the closest path to the bottom.

0

u/[deleted] Jul 08 '24

[deleted]

3

u/trajo123 Jul 08 '24

Not really, OP shows lack of understanding of fundamental concepts related to optimization.