Skip to content

Lesson 3 · Optimization I

⏱ 26 min read

Gradient Descent → SGD → Learning Rate → Mini-batch → Momentum → AdaGrad → Adam

Our main task today is not to memorize seven names, but to see how one inconvenience leads us to the next method.


1. Where we stand after linear regression

In the previous lecture we had a model. It takes the features of an object:

\[ x \]

and, using the model parameters, produces a prediction:

\[ \hat y \]

Then we compare the prediction with the true answer \(y\) and obtain the loss — the loss function. For example, for linear regression we used MSE:

\[ MSE = \frac{1}{n}\sum_{i=1}^{n}(y_i-\hat y_i)^2 \]

The main idea was:

the smaller the loss, the better the model describes our data.

And now a completely natural question arises:

How do we choose the model parameters so that the loss becomes as small as possible?

This is where we arrive at optimization.


2. What optimization is

2.1. A very human definition

Optimization is the search for the value of the parameters at which the objective function takes the value we want, usually a minimum.

In our case:

we are looking for the model parameters at which the loss function is minimal.

That is, before we had:

\[ \text{parameters} \rightarrow \text{model} \rightarrow \text{prediction} \rightarrow \text{loss} \]

And now we need to learn to move backwards:

\[ \text{loss} \rightarrow \text{how should the parameters change so that the loss decreases?} \]

2.2. The objective function

The objective function is the function we want to optimize. In ML it is often the loss function.

For example:

\[ L(w) \]

Here:

  • \(L\) — loss;
  • \(w\) — a model parameter.

Suppose:

\[ L(w)=w^2 \]

Let us look at a few values:

\(w\) \(L(w)=w^2\)
-3 9
-2 4
-1 1
0 0
1 1
2 4
3 9

The minimum here is obvious:

\[ w=0 \]

because:

\[ L(0)=0 \]

3. Global and local minimum

This is an important distinction.

Global minimum

This is the lowest point of the function overall. Imagine a vast mountain landscape.

The lowest basin in the whole area is the global minimum.

Local minimum

This is a low point within some neighborhood, but somewhere else there may be an even deeper basin. For example:

        /\              /\
       /  \    /\      /  \
      /    \__/  \____/    \
           ↑
        local
        minimum
                         ↑
                    global
                    minimum

In real ML, loss functions can be very complex. So we usually cannot simply say:

“Here is the graph of the function, let us look at it and pick the lowest point.”

We may have:

  • millions of parameters;
  • an enormous parameter space;
  • a complex loss function.

So we need a search algorithm. And this is where the derivative comes in.


4. Before Gradient Descent: the derivative

This is one of the fundamental moments of the whole lecture.

4.1. What a derivative is in plain words

The derivative shows:

how a function changes if we change its input a little.

Very important:

what changes with respect to what?

For example:

\[ y=f(x) \]

Here:

  • \(x\) — the input;
  • \(y\) — the result of the function.

The derivative:

\[ \frac{dy}{dx} \]

reads:

“how much \(y\) changes when \(x\) changes”.

That is, we are asking:

If we change \(x\) a little, what happens to \(y\)?


5. The intuition of slope

Imagine a road. If you stand on the road:

        /
       /
      /
     /
    /

and move to the right — the road rises. So the slope is positive.

If:

    \
     \
      \
       \

moving to the right makes the road descend. The slope is negative.

And if:

────────────

it is horizontal. The slope is zero.

This is a very good first intuition for the derivative.


6. Positive, negative and zero derivative

Consider:

\[ f(w)=w^2 \]

Its derivative:

\[ f'(w)=2w \]

Three cases for the sign of the derivative:

  • \(w>0\) — for example, with \(w=3\) we get \(f'(3)=6\): the derivative is positive, so as we move to the right the function grows;
  • \(w<0\) — for example, with \(w=-3\) we get \(f'(-3)=-6\): the derivative is negative, so as we move to the right the function decreases;
  • \(w=0\) — here \(f'(0)=0\): the function is horizontal, and for our function \(w=0\) is precisely the minimum.

7. Why does the derivative help us find the minimum?

This is where the most interesting part begins. We need to reduce the loss.

The derivative tells us:

in which direction the function grows.

And we need to go where it decreases. Therefore:

to find a minimum, we must move in the direction opposite to the derivative.

That is practically the whole philosophy of Gradient Descent. But so far we have only one parameter.

In a real model there are many parameters. For example:

\[ w_1,\ w_2,\ w_3,\ldots,w_{1000000} \]

What do we do then? The derivative is no longer enough.

We need the gradient.


8. Derivative vs gradient

A very important distinction.

One variable

We have:

\[ L(w) \]

Then we have one derivative:

\[ \frac{dL}{dw} \]

Several variables

Suppose:

\[ L(w_1,w_2) \]

Now the function depends on two parameters at once. We want to know:

  • how the loss changes when \(w_1\) changes;
  • how the loss changes when \(w_2\) changes.

We get two derivatives:

\[ \frac{\partial L}{\partial w_1} \]

and

\[ \frac{\partial L}{\partial w_2} \]

We combine them into a single object:

\[ \nabla L= \begin{pmatrix} \frac{\partial L}{\partial w_1}\\ \frac{\partial L}{\partial w_2} \end{pmatrix} \]

This is the gradient.


9. What a gradient is in human language

The gradient is a vector that tells us:

in which direction the function increases fastest and how strongly it changes with respect to each parameter.

For example:

\[ \nabla L= \begin{pmatrix} 5\\ 2 \end{pmatrix} \]

This means:

  • a change in \(w_1\) strongly affects the loss;
  • a change in \(w_2\) also affects it, but more weakly;
  • the direction of the fastest increase of the function is associated with the vector \((5,2)\).

And we want a minimum. So we go:

\[ -\nabla L \]

That is, against the gradient.


10. A very important picture in your head

Imagine that we are on the slope of a mountain. We need to go down.

The gradient says:

“Here is the direction in which the surface rises fastest.”

So the step must be taken in the opposite direction:

“Then let us not follow the gradient, but go against it.”

That is exactly why:

\[ \boxed{\text{Gradient Descent} = \text{movement against the gradient}} \]

11. Gradient Descent

Now we are finally ready for the algorithm itself.

Gradient Descent is an optimization algorithm that iteratively changes the parameters in the direction opposite to the gradient of the loss function.

The main formula:

\[ \boxed{ w := w-\eta\nabla L(w) } \]

At first glance it looks scary. In fact, we will now go through literally every symbol.


12. Breaking down the formula

\[ w := w-\eta\nabla L(w) \]

\(w\).

These are the model parameters. For example:

\[ w=5 \]

or, if there are many parameters:

\[ w= \begin{pmatrix} w_1\\ w_2\\ w_3 \end{pmatrix} \]

\(L\).

This is the loss function. It tells us how badly the model is doing.


\(\nabla L(w)\).

This is the gradient of the loss function with respect to the parameters \(w\). It gives the direction in which the loss grows fastest.


\(\eta\).

This is the learning rate. In plain terms:

the learning speed / the step size.

We will look at it in detail in a few minutes.


The minus sign

This:

\[ - \]

says:

go against the gradient.

Because the gradient points upward, and we need to go down.


\(w :=\).

This means:

replace the old value of \(w\) with a new one.

You can read it mentally as:

“The new \(w\) equals the old \(w\) minus ...”


13. One real numerical step

Take:

\[ L(w)=w^2 \]

Then:

\[ L'(w)=2w \]

Let:

\[ w=4 \]

Then:

\[ L(4)=16 \]

The gradient:

\[ L'(4)=8 \]

Let the learning rate be:

\[ \eta=0.1 \]

We update:

\[ w_{\text{new}} = 4-0.1\cdot8 \]
\[ w_{\text{new}}=3.2 \]

We were at:

\[ w=4 \]

and moved to:

\[ w=3.2 \]

The loss was:

\[ 16 \]

The new loss:

\[ 3.2^2=10.24 \]

That is:

\[ 16\rightarrow10.24 \]

The loss decreased.


14. A few more steps

Let us continue.

Step 1

\[ w=4 \]
\[ L=16 \]

gradient:

\[ 8 \]

we get:

\[ w=3.2 \]

Step 2

Now:

\[ w=3.2 \]

gradient:

\[ 2\cdot3.2=6.4 \]

We update:

\[ 3.2-0.1\cdot6.4 \]
\[ =2.56 \]

Loss:

\[ 2.56^2=6.5536 \]

Step 3

\[ w=2.56 \]

gradient:

\[ 5.12 \]

New value:

\[ 2.56-0.1\cdot5.12=2.048 \]

Loss:

\[ 2.048^2\approx4.19 \]

So we get:

Step \(w\) Loss
0 4 16
1 3.2 10.24
2 2.56 6.55
3 2.048 4.19

We are gradually approaching:

\[ w=0 \]

and the loss is approaching:

\[ 0 \]

15. Iteration, step and convergence

It is easy to get confused here.

Iteration

Iteration is one iteration of the algorithm.

That is, one cycle:

  1. compute the gradient;
  2. update the parameters.

Step

Step literally means a step.

In the context of optimization people often mean the same parameter update:

the optimizer took one step.

For example:

\[ w=4\rightarrow3.2 \]

is one step.


Convergence

Convergence is the situation where the optimization process gradually approaches a stable solution.

For example:

\[ 4 \rightarrow 3.2 \rightarrow 2.56 \rightarrow 2.048 \rightarrow ... \rightarrow 0 \]

The changes become smaller and smaller, and we approach the minimum.


16. Learning rate

Now a very important part. In the formula:

\[ w:=w-\eta\nabla L \]

\(\eta\) is the learning rate. It determines:

how strongly we react to the gradient in one step.

Very important:

Gradient ≠ learning rate ≠ step

These are three different things.


Gradient

The gradient answers:

which way should we move, and how strongly does the function change in that direction?


Learning rate

The learning rate answers:

how much do we trust that direction, and how large a step do we take?


Step

A step is the parameter update itself. For example: \(\eta=0.1\) and \(gradient=8\) then the amount of change is:

\[ 0.1\cdot8=0.8 \]

And we go:

\[ 4\rightarrow3.2 \]

17. What if the learning rate is too small?

Suppose:

\[ \eta=0.000001 \]

There is a gradient. The direction is correct.

But the step is tiny. So we get:

        minimum
          ↓
• → • → • → • → • → •

We are moving in the right direction, but very slowly. As a result, training may require an enormous number of iterations.


18. And what if the learning rate is too large?

Now:

\[ \eta=2 \]

Let us go back to:

\[ L(w)=w^2 \]

and:

\[ w=4 \]

The gradient:

\[ 8 \]

The update:

\[ 4-2\cdot8 \]
\[ = -12 \]

We wanted to get closer to:

\[ 0 \]

but we jumped to:

\[ 4\rightarrow-12 \]

Now the gradient is:

\[ -24 \]

The next step:

\[ -12-2(-24) \]
\[ =36 \]

Then:

\[ 36-2(72)=-108 \]

So we get:

\[ 4\rightarrow-12\rightarrow36\rightarrow-108\rightarrow... \]

We are not approaching the minimum. We are flying away from it.


19. Why can't we always use an enormous learning rate?

One loss landscape and three descent trajectories: too small a step, a good step, and a diverging step
Three learning-rate regimes on a single landscape. The blue trajectory is a step that is too small: the direction is right, but the movement is slow. The dark one is a good step: a few confident steps to the minimum. The red one is a step that is too large: the point overshoots the minimum, the swing grows, and training diverges. Hence the rule: a learning rate is tuned, not guessed.

Because gradient descent is not teleportation to the minimum. We take consecutive steps.

If the step is too large:

             minimum
               ↓
------•----------------
      ↘
        ↘
          ↘
            •

we may overshoot the minimum. And start bouncing from one side to the other.

That is why the learning rate is one of the most important hyperparameters of training.


20. Dataset, batch, iteration, epoch

Now another group of terms appears. Imagine:

\[ 1000 \]

training objects. This is our dataset.

Dataset

Dataset is a set of data.


Batch

A batch is a group of objects that we use for one gradient computation.


Batch size

Batch size is how many objects are in one batch.

For example:

\[ batch\ size=100 \]

Epoch

Epoch is one full pass over the whole training dataset.

That is, we want the model to see all 1000 objects once.


Iteration

One iteration is one parameter update.


21. Example: 1000 objects, batch size = 100

We have:

\[ N=1000 \]

and:

\[ batch\ size=100 \]

How many batches are in one epoch?

\[ \frac{1000}{100}=10 \]

So:

1 epoch = 10 batches.

If we update the parameters after every batch:

1 epoch = 10 updates.

If we did 5 epochs:

\[ 5\cdot10=50 \]

updates.


22. Full Batch Gradient Descent

So far we have spoken somewhat abstractly about “computing the gradient”. But on which data?

In classical Batch Gradient Descent we take:

the entire training dataset.

For example:

\[ 1000000 \]

objects. We:

  1. take a million objects;
  2. compute predictions;
  3. compute the loss;
  4. compute the gradient;
  5. update the parameters.

And only after that do we take the next step.


Upside

The gradient turns out to be relatively stable. We use all the information.


Downside

It can be expensive. If the dataset is huge, every step requires processing an enormous amount of data.

So we get:

to make one parameter update, we process the entire dataset every time.

And a natural question arises:

Do we really have to look at all the data every time?


23. SGD — Stochastic Gradient Descent

This is where the next method appears.

SGD = Stochastic Gradient Descent.

The main idea:

instead of the whole dataset, use one object to compute one update.

Suppose there are:

\[ 1000000 \]

objects. Instead of this:

flowchart TD
    N1["all 1,000,000"] --> N2["gradient"] --> N3["update"]

we do this:

flowchart TD
    A1["object 1"] --> A2["gradient"] --> A3["update"] --> A4["object 2"]
flowchart TD
    B1["gradient"] --> B2["update"] --> B3["object 3 …"]

And so on.


24. Why is it called stochastic?

Stochastic means “random / probabilistic”.

Because a single object is only a tiny part of all the information. Suppose we have 1000 objects.

One object may say:

“The parameter should move to the right.”

Another:

“No, a bit to the left.”

A third:

“To the right.”

So the direction starts to wobble a little.


25. What “noise” means in SGD

Very important.

Noise here does not mean a bug in the program.

It means:

the gradient computed from one random object differs from the gradient we would get from the whole dataset.

For example, the full dataset says:

\[ gradient=5 \]

While individual objects give:

\[ 7,\quad 3,\quad 6,\quad 4,\quad 8,\ldots \]

Each individual gradient reflects the overall picture imprecisely. So the movement turns out to be:

       ↗
     ↗
   → 
     ↗
   ↘
     ↗
       →
         ↗

rather than perfectly straight.


26. Batch GD vs SGD

Property Batch GD SGD
Data per update the whole dataset 1 object
Cost of one update high low
Updates rare very frequent
Direction stable noisy
Oscillations fewer more
Large datasets expensive more convenient
Parallel computation possible less convenient

But here a third option appears.


27. Mini-batch Gradient Descent

Instead of:

  • the whole dataset

or:

  • one object

let us take:

a small group of objects.

For example:

\[ batch\ size=32 \]

This is called a mini-batch. This is exactly the approach that is very widespread in practical ML.


28. Why is mini-batch convenient?

Imagine:

\[ 1000 \]

objects. And:

\[ batch\ size=32 \]

Then in one epoch we will process:

\[ \frac{1000}{32} \approx31.25 \]

That is, there will be 32 batches, if the last batch is incomplete and we use it too. So we get roughly:

\[ 32 \]

updates per epoch.


29. What happens inside one epoch

Suppose:

flowchart TD
    A["1000 objects<br/>32 batches of 32"] --> B["each batch:<br/>gradient → update"] --> C["one epoch = 32 updates"]

After that:

the model has gone through the whole dataset once.

This is one epoch.


30. Why is mini-batch especially convenient for a GPU?

A GPU is very good at performing the same operations on many numbers at once. For example:

flowchart TD
    N1["32 objects"] --> N2["matrix operations"] --> N3["32 predictions"]

instead of processing every object completely separately. So mini-batch gives a good compromise:

enough data for a relatively stable gradient + a small enough volume for efficient computation.


31. The main idea of the three approaches

Three panels with descent trajectories: full batch, SGD over one object, and mini-batch
Three ways to compute the gradient. On the left, full batch: one step over the whole dataset — the trajectory is smooth, but every step is expensive. In the middle, SGD: a step per single object — the trajectory shakes, but the steps are cheap and there are many of them. On the right, mini-batch: a few dozen objects per step — the movement is almost smooth and still fast. It is mini-batch that gets used in practice.

You can remember it like this:

  • Batch GD — “I'll look at everyone, then take one step.”
  • SGD — “I'll look at one, and take a step right away.”
  • Mini-batch — “I'll look at a small group, then take a step.”

32. Why does SGD work at all if the gradient is noisy?

A very good question. Suppose there are 1000 objects.

The full dataset shows:

\[ \text{direction roughly to the right} \]

But individual objects may give:

↗
→
↘
↗
→
↗

So some steps are imperfect. But if the data is informative overall, then on average these directions reflect the general trend.

That is, an individual object may be wrong relative to the overall picture, but many such observations together let us move in a useful direction.


33. And noise is sometimes useful

This is a little unexpected. If the movement is fully deterministic and we land in an awkward region, a little noise can help us get out of it.

Imagine a small shallow dip:

       \      /
        \____/
           \
            \________

Noisy steps sometimes keep us from getting too “stuck” in places like that. But:

noise is not a magical blessing.

Too much noise is bad as well.


34. Why did we need the next optimizers at all?

By now we already have Gradient Descent. But problems arise.

  1. sometimes the movement is very slow.
  2. sometimes the parameters start to oscillate heavily.
  3. there are ravines.
  4. different parameters may have completely different scales.
  5. some gradients may be very small.

And then the question arises:

Can we use not only the current gradient, but also the history of previous steps?

Yes. That is how we arrive at Momentum.


35. Ravine

A narrow elongated valley: one trajectory zigzags while a second one with momentum runs along the bottom
A ravine: why plain descent spins its wheels. A narrow elongated valley: the function changes steeply in one direction and almost flatly in the other. A trajectory with no memory bounces from wall to wall and crawls slowly toward the bottom. A trajectory with momentum accumulates direction and runs almost straight along the bottom. Momentum does not change the minimum — it changes the path to it.

Imagine a long narrow valley:

        \                         /
         \                       /
          \_____________________/

But now let us look at it from above:

        \       /
         \     /
          \   /
           \ /
           / \
          /   \

In one direction the function changes very strongly. In the other — very slowly.

For example:

change along X: huge
change along Y: small

The gradient reacts to the current slope. So the algorithm may start doing this:

↘
↗
↘
↗
↘
↗

instead of moving calmly along the valley. This is one of the intuitions behind the ravine problem.


36. Momentum

Now let us imagine a physical object. Imagine a ball rolling down a slope.

It has not only the current direction of force, but also the inertia of motion. If it has already been moving to the right several times, the new movement will take that into account too.

The idea of Momentum:

do not forget the previous directions of movement entirely.


37. What does Momentum give us?

Imagine that the gradient is noisy:

→
↗
→
↘
→
↗

Plain SGD may jerk around. Momentum says:

“A new gradient does not cancel the previous movement.”

It accumulates information about the direction.


38. The intuitive Momentum formula

One common way to write it:

\[ v_t=\beta v_{t-1}+\nabla L(w_t) \]

and then:

\[ w_{t+1}=w_t-\eta v_t \]

There is no need to be intimidated. Let us break it down.

Обозначение Что значит
\(v_t\) this is a conventional velocity / accumulated direction of movement
\(v_{t-1}\) the previously accumulated direction
\(\beta\) how strongly we retain the old information
\(\nabla L\) the current gradient
\(\eta\) the learning rate

39. What does β do?

Imagine:

\[ \beta=0.9 \]

This roughly means:

the past direction carries a large weight.

If:

\[ v_{t-1}=10 \]

and the new gradient is:

\[ g_t=2 \]

then:

\[ v_t=0.9\cdot10+2 \]
\[ v_t=11 \]

The new movement does not start from zero. It continues the direction that already exists.


40. Why does Momentum reduce oscillations?

Suppose that along one direction the gradients often change sign:

\[ +5,-5,+5,-5 \]

They will partially cancel each other out. While if in another direction the gradient is stable:

\[ +2,+2,+2,+2 \]

then Momentum will accumulate that direction. Intuitively we get:

a stable direction is amplified, chaotic changes are smoothed out.


41. But Momentum solves one problem, not all of them

We have gained:

memory of the previous movement.

But another problem remains. Suppose:

\[ w_1 \]

needs a small step, while

\[ w_2 \]

needs a larger one. And we have a single:

\[ \eta \]

That is, one shared learning rate. The question arises:

Can we tune the step size automatically for different parameters separately?

Yes. And this is where the adaptive learning rate comes in.


42. Adaptive Learning Rate

Adaptive means adjusting depending on the situation.

Instead of:

\[ \eta \]

for all parameters, we want something like:

\[ \eta_1,\eta_2,\eta_3,\ldots \]

That is:

each parameter gets its own effective step size.

Why can this be useful? Because parameters can behave in completely different ways.

For example:

w1: gradients are large
w2: gradients are small

If we use the same learning rate, one parameter may get too harsh a step and another too slow a one.


43. AdaGrad

AdaGrad = Adaptive Gradient.

The main idea:

parameters that have accumulated large gradients get ever smaller effective steps.

Very roughly:

flowchart TD
    N1["large past gradients"] --> N2["large accumulated scale"] --> N3["smaller step"]

And for a parameter whose gradients are small:

flowchart TD
    N1["small past gradients"] --> N2["smaller accumulated scale"] --> N3["a relatively larger step"]

44. The AdaGrad formula

Simplified:

\[ G_t=G_{t-1}+g_t^2 \]

and:

\[ w_{t+1} = w_t- \frac{\eta}{\sqrt{G_t}+\epsilon}g_t \]

Now piece by piece.


\(g_t\).

The current gradient.


\(g_t^2\).

The square of the gradient. It makes the values positive and lets us accumulate the magnitude of the gradients.


\(G_t\).

The accumulated sum of squared gradients:

\[ G_t=G_{t-1}+g_t^2 \]

So the algorithm keeps a history.


\(\sqrt{G_t}\)

We take the root of the accumulated value.


\(\epsilon\)

A very small positive number. For example:

\[ 10^{-8} \]

It is needed, in particular, to avoid division by zero.


45. Why does AdaGrad reduce the step?

Let us look at:

\[ \frac{\eta}{\sqrt{G_t}+\epsilon} \]

The larger:

\[ G_t \]

becomes, the larger the denominator. Which means:

\[ \frac{\eta}{\sqrt{G_t}+\epsilon} \]

becomes smaller. So the effective learning rate decreases.


46. The problem with AdaGrad

Here an important drawback appears. We keep doing:

\[ G_t=G_{t-1}+g_t^2 \]

That is, \(G_t\) only grows. It does not forget old gradients.

So over time the denominator can become very large. And the effective step:

\[ \frac{\eta}{\sqrt{G_t}+\epsilon} \]

becomes very small. At some point:

the model may practically stop moving.

That is exactly why AdaGrad can adapt steps well, but become too cautious over time.


47. And this is where Adam appears

We have already obtained two very useful ideas.

Momentum

Wants:

to take past directions of movement into account.

AdaGrad

Wants:

to adapt the step size for different parameters.

A natural idea arises:

What if we combine these approaches?

That is exactly what underlies Adam.


48. Adam

The name:

Adam = Adaptive Moment Estimation.

For teaching intuition, it is convenient to see it as a combination of:

\[ \boxed{ \text{a Momentum-like idea} + \text{Adaptive learning rate} } \]

This matches precisely the logical chain we are building in this lecture.


49. Two things Adam remembers

Adam keeps two moving estimates. The first is related to the gradient itself.

The second — to the square of the gradient. Let us denote them:

\[ m_t \]

and

\[ v_t \]

50. The first estimate: \(m_t\).

The formula:

\[ m_t=\beta_1m_{t-1}+(1-\beta_1)g_t \]

This is similar to Momentum. We mix:

  • the old information;
  • the current gradient.

\(m_t\) can intuitively be understood as:

a smoothed direction of the gradient.


51. What does β₁ do?

\[ \beta_1 \]

determines how strongly we take the past into account. A common choice is:

\[ \beta_1=0.9 \]

That is, the past carries a large weight.


52. The second estimate: \(v_t\).

Now:

\[ v_t= \beta_2v_{t-1} + (1-\beta_2)g_t^2 \]

Here we already use:

\[ g_t^2 \]

That is, the square of the gradient. This quantity helps estimate the scale of the gradients.


53. What does β₂ do?

\[ \beta_2 \]

determines how strongly we retain the past information about the squared gradient. A common choice is:

\[ \beta_2=0.999 \]

That is, this estimate changes rather smoothly.


54. Why two estimates specifically?

A very useful intuition:

\(m_t\)

roughly answers the question:

Where are we heading on average?

\(v_t\)

roughly answers the question:

What was the scale of the gradients?

And then Adam uses both pieces of information to determine the update.


55. But why do bias corrections appear?

This is the place that is often explained too fast. The problem arises at the very beginning.

Initially:

\[ m_0=0 \]
\[ v_0=0 \]

And then we start updating them. Since we started from zero, the first estimates may be biased toward zero.

So Adam corrects them. We get:

\[ \hat m_t= \frac{m_t}{1-\beta_1^t} \]

and:

\[ \hat v_t= \frac{v_t}{1-\beta_2^t} \]

56. What is bias correction in plain words?

You do not need to memorize it as a magic formula just yet. The idea:

at the beginning we do not yet have enough history, and our moving estimates are artificially pulled toward zero, because we started from zeros.

Bias correction compensates for this initial effect.


57. The final Adam formula

After computing:

\[ m_t \]
\[ v_t \]

and correcting them:

\[ \hat m_t \]
\[ \hat v_t \]

we get the update:

\[ \boxed{ w_{t+1} = w_t - \eta \frac{\hat m_t} {\sqrt{\hat v_t}+\epsilon} } \]

Let us break it down:

Обозначение Что значит
\(w_t\) the current parameters
\(\eta\) the base learning rate
\(\hat m_t\) the corrected smoothed direction of the gradient
\(\hat v_t\) the corrected estimate of the scale of the squared gradients
\(\sqrt{\hat v_t}\) scales the step
\(\epsilon\) protects against division-by-zero problems

58. The whole evolution now looks logical

This is really important to see. We started with:

Gradient Descent

Let us move against the gradient.

But:

it can be expensive.

↓

SGD

Let us compute the gradient on a single object.

But:

the movement became noisy.

↓

Mini-batch

Let us take a small group.

We got:

a compromise between cost and stability.

But:

the movement may oscillate and be slow.

↓

Momentum

Let us take the past direction into account.

It became:

smoother and often faster.

But:

different parameters may need different step scales.

↓

AdaGrad

Let us adapt the steps for different parameters.

But:

the accumulated sum of gradients keeps growing.

↓

Adam

Let us use a smoothed direction and an adaptive step scale at the same time.

This is the logic, not a list of names.


59. The big table of optimizers

Method Main idea What it stores How it changes the step
Batch GD use the whole dataset nothing from the history one shared LR
SGD a single object nothing from the history one shared LR
Mini-batch a small group nothing from the history one shared LR
Momentum take past movement into account velocity/momentum the step depends on the accumulated direction
AdaGrad adapt the step the sum of squared gradients reduces the step more strongly for frequently large gradients
Adam combine the two ideas \(m_t\) and \(v_t\) adapts the step + smooths the direction

60. A very important distinction between these concepts

This is really worth learning conceptually.

Gradient Descent

This is the general idea:

move against the gradient.


SGD

In the classical sense:

use a single object to estimate the gradient at each update.


Mini-batch

use a small group of objects.

This is not necessarily “a completely different philosophical algorithm” — it is a way of computing the gradient in practice.


Momentum

a mechanism that takes previous directions into account.


AdaGrad

a mechanism for adapting the effective step based on the history of squared gradients.


Adam

a mechanism that uses a smoothed gradient direction and step adaptation based on its scale.


61. A practical example: \(f(w)=w^2\).

Let us return to our simple function:

\[ f(w)=w^2 \]

The derivative:

\[ f'(w)=2w \]

Let:

\[ w_0=4 \]

and:

\[ \eta=0.1 \]

The first step

\[ gradient=2\cdot4=8 \]
\[ w_1=4-0.1\cdot8 \]
\[ w_1=3.2 \]

Loss:

\[ f(3.2)=10.24 \]

The second step

\[ gradient=2\cdot3.2=6.4 \]
\[ w_2=3.2-0.1\cdot6.4 \]
\[ w_2=2.56 \]

Loss:

\[ f(2.56)=6.5536 \]

The third step

\[ gradient=5.12 \]
\[ w_3=2.048 \]

Loss:

\[ \approx4.19 \]

That is:

w:
4
↓
3.2
↓
2.56
↓
2.048
↓
... loss:
16
↓
10.24
↓
6.55
↓
4.19
↓
...

This is the physical mechanics of Gradient Descent.


62. And where is all this in a neural network?

Now let us carefully connect this to what comes next.

A neural network has parameters: \(W_1,W_2,\ldots\) and biases: \(b_1,b_2,\ldots\). After the forward pass the model produces a prediction.

We compare the prediction with the correct answer. We get:

\[ Loss \]

Then the gradients of the loss function with respect to the parameters are computed. Simplified:

flowchart TD
    A1["data"] --> A2["neural network"] --> A3["prediction"] --> A4["loss"]
flowchart TD
    B1["gradient"] --> B2["optimizer"] --> B3["new parameters"]

The Optimizer may be, for example, Adam. So the optimizer is responsible for:

how to change the model parameters using the computed gradients.


And backpropagation?

For now, just the minimum:

Backpropagation is the mechanism for computing the gradients of a neural network's parameters.

And the optimizer then uses those gradients to update the parameters. We will not go into backpropagation in detail here — that is a separate topic.


63. What you need to be able to do in an ML interview

First try to answer on your own, without peeking.

Basic level

  1. What is Gradient Descent?
  2. What is a gradient?
  3. Why do we move against the gradient?
  4. What is a learning rate?
  5. What happens with too large a learning rate?
  6. What happens with too small a learning rate?

Intermediate level

  1. How does SGD differ from Batch Gradient Descent?
  2. What is a mini-batch?
  3. What is a batch?
  4. What is an epoch?
  5. What is an iteration?
  6. Why do we need Momentum?

Advanced level

  1. What does AdaGrad do?
  2. Why can AdaGrad gradually stop training the model?
  3. What is the idea behind Adam?
  4. Which two quantities does Adam track?
  5. Why does Adam use \(\beta_1\) and \(\beta_2\)?
  6. What is bias correction?
  7. Why is SGD noise not necessarily bad?
  8. What does the rate of convergence depend on?

64. Model answers

Now the answers, so you can compare them with your own.

1. What is Gradient Descent?

Gradient Descent is an optimization algorithm that changes the model parameters in the direction opposite to the gradient of the loss function in order to reduce the loss.


2. What is a gradient?

The gradient is a vector of partial derivatives of a function with respect to its parameters. It points in the direction of the fastest increase of the function.


3. Why do we move against the gradient?

Because the gradient points in the direction of the fastest increase of the loss, and we need to reduce the loss.


4. What is a learning rate?

The learning rate is the quantity that determines the step size when updating the parameters.


5. Too large a learning rate

The steps may become too large: the algorithm may overshoot the minimum, oscillate or diverge.


6. Too small a learning rate

Training may be very slow and require a large number of iterations.


7. SGD vs Batch GD

Batch GD computes the gradient over the whole dataset before updating the parameters. SGD uses a single object to estimate the gradient and updates the parameters after each such object.


8. Mini-batch

A small group of objects used for one gradient computation and one parameter update.


9. Batch

A group of data objects processed together.


10. Epoch

One full pass over the whole training dataset.


11. Iteration

One iteration of the parameter update.


12. Momentum

Momentum uses information about previous directions of movement to smooth out oscillations and speed up movement in a stable direction.


13. AdaGrad

AdaGrad adapts the effective learning rate for each parameter using accumulated information about past squared gradients.


14. Why can AdaGrad stop?

Because the accumulated sum of squared gradients keeps growing. It increases the denominator in the update formula, so the effective step gradually becomes very small.


15. Adam

Adam combines the idea of smoothing the gradient direction, similar to Momentum, with adaptive step scaling.


16. What does Adam track?

Two quantities: \(m_t\) — a smoothed estimate of the gradient, and \(v_t\) — a smoothed estimate of the squared gradient.


17. \(\beta_1\) and \(\beta_2\).

They control how strongly past values influence the current estimates.


18. Bias correction

It corrects the initial bias of the estimates \(m_t\) and \(v_t\), which arises because they are initialized to zero.


65. Self-check problems

Answer each task for yourself, then open the answer and compare. You do not have to solve it perfectly — the goal is to see where the gaps are.

Problem 1 — one step

Given \(L(w)=w^2\) \(w=5\) \(\eta=0.1\). Find:

  1. the gradient;
  2. the new \(w\);
  3. the new loss.
Show answer
\[ L(w)=w^2 \]

The derivative:

\[ L'(w)=2w \]

At:

\[ w=5 \]

we get:

\[ g=10 \]

The update:

\[ w_{new}=5-0.1\cdot10 \]
\[ w_{new}=4 \]

The new loss:

\[ L(4)=16 \]

Before the update:

\[ L(5)=25 \]

That is:

\[ 25\rightarrow16 \]

Problem 2 — direction

The derivative at the current point is \(L'(w)=-4\). Which way should the parameter \(w\) move if we want to decrease the function?

Left or right?

Show answer

The derivative:

\[ -4 \]

It is negative. This means that as we move to the right, the function decreases.

So to decrease the function we move:

to the right.

This is a very important point. Do not memorize:

“a negative derivative = go left”.

On the contrary, look at the formula:

\[ w_{new}=w-\eta g \]

If:

\[ g=-4 \]

then:

\[ w_{new}=w-\eta(-4) \]
\[ =w+4\eta \]

That is, \(w\) increases.

Problem 3 — learning rate

We have \(gradient=3\).

Compare two learning rates: \(\eta_1=0.1\) and \(\eta_2=1\). How will the step size change?

Show answer

At:

\[ g=3 \]

and:

\[ \eta=0.1 \]

the size of the change is:

\[ 0.3 \]

At:

\[ \eta=1 \]

the size of the change is:

\[ 3 \]

That is, the second step is 10 times larger.

Problem 4 — batches

The dataset contains \(1000\)

objects. \(batch\ size=50\). How many batches will there be in one epoch?

How many parameter updates will happen per epoch if an update is performed after every batch?

Show answer
\[ 1000/50=20 \]

We get:

20 batches per epoch.

If there is an update after every batch:

20 updates.

Problem 5 — a bit harder

Dataset \(1030\)

objects.

Batch size \(100\). How many batches will be needed if the last incomplete batch is used as well?

Show answer
\[ 1030/100=10.3 \]

The first 10 batches contain:

\[ 1000 \]

objects. What remains is:

\[ 30 \]

So:

11 batches.

The last one contains 30 objects.

Problem 6 — Momentum

We have \(v_{t-1}=10\) \(\beta=0.9\) \(g_t=2\). We use \(v_t=\beta v_{t-1}+g_t\). Find \(v_t\).

Show answer
\[ v_t=0.9\cdot10+2 \]
\[ v_t=11 \]

Problem 7 — conceptual

Why can SGD move not straight toward the minimum, but roughly like this:

```text
↗ → ↘ ↗ → ↗ ↘ → ↗
```

And why does this not mean the algorithm is broken?

Show answer

Because with SGD the gradient is computed from one object, not from the whole dataset. A single object gives only an approximate direction.

So individual steps may deviate. This is the noise of SGD.

Problem 8 — AdaGrad

Why does the denominator in AdaGrad gradually increase?

What happens to the effective step size because of that?

Show answer

Because:

\[ G_t=G_{t-1}+g_t^2 \]

That is, the squared gradients keep accumulating. The denominator becomes larger.

The effective step becomes smaller.

Problem 9 — Adam

Fill in the blank:

Adam can intuitively be seen as a combination of the idea of _ and the idea of _.

Show answer

The answer:

Momentum + adaptive learning rate.

More precisely:

a smoothed estimate of the gradient direction + adaptive step scaling.

67. The most important map of the whole lecture

Now let us assemble everything into one chain.

And now the most important thing — why we moved from one to the next:

  1. Loss

    We need to measure how badly the model is doing.

    ↓

  2. Optimization

    We need to find the parameters at which the loss is minimal.

    ↓

  3. Derivative

    We need to understand how the function changes.

    ↓

  4. Gradient

    There are many parameters, so we need information about each of them.

    ↓

  5. Gradient Descent

    We use the gradient to move toward a smaller loss.

    ↓

  6. Learning Rate

    We need to determine the step size.

    ↓

  7. SGD

    The full dataset may be too expensive for every update.

    ↓

  8. Mini-batch

    A single object is too noisy, the whole dataset is too expensive → we take a compromise.

    ↓

  9. Momentum

    Even then the movement may oscillate → we use information about the previous movement.

    ↓

  10. Adaptive Learning Rate

    Different parameters may need different effective step sizes.

    ↓

  11. AdaGrad

    We adapt the steps based on the history of gradients.

    ↓

  12. Adam

    We want to use direction smoothing and step-scale adaptation at the same time.


68. A compact cheat sheet

Gradient Descent

\[ w_{t+1}=w_t-\eta\nabla L(w_t) \]

Idea: move against the gradient.


Gradient

\[ \nabla L= \begin{pmatrix} \frac{\partial L}{\partial w_1}\\ \frac{\partial L}{\partial w_2}\\ \vdots \end{pmatrix} \]

Idea: it points in the direction of the fastest increase of the function.


Learning rate

\[ \eta \]

Idea: the step size.


Batch GD

Uses the whole dataset for one update.


SGD

Uses a single object.


Mini-batch

Uses a small group of objects.


Momentum

Keeps information about the previous direction of movement. Intuitively:

“don't forget where we have already been heading”.


AdaGrad

Accumulates squared gradients:

\[ G_t=G_{t-1}+g_t^2 \]

and adapts the effective step. The problem:

the step may become too small over time.


Adam

Stores:

\[ m_t \]

and:

\[ v_t \]

where:

  • \(m_t\) — smoothed information about the direction of the gradient;
  • \(v_t\) — smoothed information about the scale of the squared gradients.

Then it uses:

\[ w_{t+1} = w_t- \eta \frac{\hat m_t} {\sqrt{\hat v_t}+\epsilon} \]

69. What should stay in your head after this lecture

Not seven names:

Gradient Descent, SGD, Mini-batch, Momentum, AdaGrad, Adam...

But this:

We have a loss. We want to reduce it.

To do that we need to understand:

which way should the parameters move?

The derivative/gradient gives the direction. Then:

we move against the gradient.

But:

how large a step should we take?

The learning rate. Then we notice:

we do not have to look at the whole dataset every time.

SGD and mini-batch appear. Then:

the movement may be noisy and oscillatory.

Momentum appears. Then:

different parameters may need different step scales.

AdaGrad appears. And finally:

we want to combine memory of the direction of movement with step adaptation.

Adam appears.

This cause-and-effect chain can be used both in an interview and later when studying neural networks. It is understanding “why the next method appeared”, rather than memorizing formulas, that is the main result of this lecture.

🧪 Practice

  1. Optimizer race — SGD, Momentum and Adam: you can see who cuts the path short and who wanders.
  2. Descent over the loss function — where the gradient comes from and why a large step breaks training.

Check yourself

📚 Further reading