Runoob Tutorial ArchiveEnglish

Gradient Descent - Descending along the steepest direction

Gradient Descent -- Descending along the steepest direction

This chapter implements gradient descent from scratch to fit linear regression. This is the mathematical prototype of the entire AI training loop.


Concept Analysis

Core Formula

[ \theta_{t+1} = \theta_t - \eta \nabla J(\theta_t) ]

Training Four-Step Loop

Forward Propagation

Predict output

Calculate loss

Measure the gap

Calculate gradient

Backpropagation

Update parameters

θ -= η·∇J

Effect of learning rate

Learning rate Effect
Too small Extremely slow convergence, requires many steps
Moderate Stable and fast convergence
Too large Oscillates or diverges

Real-life examples

**Descending a mountain in thick fog

In a thick fog where you can't see your hand in front of your face, you need to descend the mountain. The strategy for every step:

Feel the steepest direction under your feet → take a small step in the steepest downhill direction → stop → feel again → take another small step → repeat.

This is gradient descent: feeling = calculating the gradient, taking a small step = updating parameters, stopping = the next iteration.


Python hands-on practice

Example

import

numpy

as

np

Generate data y = 3x + 2 + noise

np.

random

.

seed

(

42

)

X

=

np.

linspace

(

0

,

10

,

100

)

y

=

3

2

random

.

normal

(

0

,

2

,

100

)

Implement gradient descent from scratch

w

,

b

=

0.0

,

0.0

lr

,

n_iter

=

0.01

,

200

losses

=

[

]

for

i

in

range

(

n_iter

)

:

y_pred

=

w * X + b

loss

=

np.

mean

(

(

y_pred - y

)

**

2

)

losses.

append

(

loss

)

   

Gradient

dw

=

2

mean

(

(

y_pred - y

)

)

db

=

2

mean

(

y_pred - y

)

   

Update

w -

=

lr * dw

b -

=

lr * db

print

(

f

"RUNOOB Gradient Descent Results:"

)

print

(

f

"True: w=3.0, b=2.0"

)

print

(

f

"Fit: w={w:.4f}, b={b:.4f}"

)

print

(

f

"Initial loss: {losses[0]:.2f} → Final loss: {losses[-1]:.2f}"

)

Original prompt (Chinese, left untranslated)



RUNOOB Gradient Descent Results:

真实: w=3.0, b=2.0

拟合: w=2.9874, b=2.2835

初始损失: 79.69 → 最终损失: 3.91

Loss decrease curve


Application scenarios in AI

Mathematical prototype of the PyTorch training loop

All deep learning training loops follow the same pattern, which is gradient descent:

① optimizer.zero_grad() → zero out the gradient cache; ② loss = model(x) → forward propagation; ③ loss.backward() → backpropagation to calculate gradients; ④ optimizer.step() → execute parameter update θ -= η·∇J.

Once you understand this four-step loop, you understand the core training logic of all deep learning frameworks.

Learning rate is the most important hyperparameter

Learning rate too large → loss oscillates or even diverges; learning rate too small → convergence is extremely slow, possibly getting stuck in a local optimum. Learning rate scheduling (Step, Cosine Annealing, Warmup) is an essential technique for training large models—GPT-3 training used a linear warmup + cosine decay strategy.

Batch size trade-off in SGD

Full GD: calculates exact gradients using all data, slow but stable; SGD (batch_size=1): looks at only one sample each time, fast but has high gradient estimation noise; Mini-batch SGD: a compromise (batch_size=32/64/128), moderate noise, which actually helps escape local optima—this is the standard practice in actual training.

Limitations of Gradient Descent

Gradient Descent finds points where the gradient is zero—which could be a global optimum, a local optimum, or a saddle point. In high-dimensional spaces, saddle points are much more common than local optima: a point is a minimum in some directions and a maximum in others. Adaptive optimizers like Adam can escape saddle points more effectively.