Skip to content
New
Latest News || 27 October 2026: Dr Soumava Mukherjee's invited talk at Queen's University Belfast joined device-level hardware innovation with channel-level control. || 22 October 2026: I received a Certificate of Appreciation for serving as a reviewer for IEEE IMAS 2026. || 15 October 2026: I presented a poster on beam-domain ML fingerprinting for RIS-aided mmWave localisation at the Centre for Wireless Innovation's annual symposium. || 15 October 2026: CWI's annual symposium brought research and industry perspectives on 6G, ISAC, optical wireless, AI, and future networks to Queen's University Belfast. || 14 October 2026: Erik Nordell of Ericsson visited our Keysight Lab for a live RIS-assisted video streaming demonstration.
Knowledge Hubmachine learning4. Gradient Descent

machine learning learning note

4. Gradient Descent

A deeper but beginner-friendly explanation of gradient descent, learning rate, optimization variants, and common training problems.

At a glance

  • Move opposite the gradientA gradient gives the local direction of fastest increase. Subtract a scaled gradient to seek lower loss.
  • Step size controls stabilityFor the lab loss (u²+4v²)/2, exact full-gradient convergence requires 0 < learning rate < 0.5.
  • Lower training loss is not enoughMonitor validation performance as well as optimization; backpropagation computes gradients and the optimizer applies updates.

What is Gradient Descent?

Gradient descent is an optimization algorithm used to reduce a model's error. It is one of the most important ideas in machine learning because many models learn by minimizing a loss function.

A loss function measures how wrong the model is. A high loss means bad predictions; a low loss means better predictions. Gradient descent changes the model parameters step by step so that the loss becomes smaller.

Imagine descending a hill using only the slope under your feet:

  • Height: model error (loss).
  • Position: current model parameters.
  • Step: adjust parameters in the local downhill direction.
References for this section3

The Core Idea

For a model parameter w, gradient descent repeats this update:

wt+1=wt−η∇L(wt)w_{t+1}=w_t-\eta\nabla L(w_t)
  • wtw_{t}: parameter before update step t.
  • wt+1w_{t+1}: parameter after update step t.
  • η\eta is the learning rate.
  • LL is the loss
  • ∇L(wt)\nabla L(w_{t}) is its gradient at the current parameter.

The gradient tells us the direction in which the loss increases fastest. Because we want the loss to decrease, we move in the opposite direction.

In compact notation:

w←w−η∂L∂ww\leftarrow w-\eta\frac{\partial L}{\partial w}
  • ww is the parameter being updated
  • η\eta controls step size.
  • ∂L/∂w\partial L / \partial w is the loss slope with respect to w.

where:

  • ww is a model parameter.
  • LL is the loss function.
  • ∂L/∂w\partial L / \partial w is the gradient of the loss with respect to w.
  • η\eta is the learning rate.

When does a downhill update overshoot and diverge?

1. Formula and symbols
L(u,v)=12(u2+4v2),∇L=[u,4v]TL(u,v)=\tfrac12(u^2+4v^2),\quad\nabla L=[u,4v]^T
ut+1=(1−η)ut,vt+1=(1−4η)vtu_{t+1}=(1-\eta)u_t,\quad v_{t+1}=(1-4\eta)v_t
  • uu: First model coordinate
  • vv: Second model coordinate
  • LL: loss
  • η\eta: learning rate
  • tt: update index

The fixed quadratic has curvatures 1 and 4, giving convergence for 0 < η < 0.5.

Equal-unit u/v contours; origin at centrelog₁₀(1 + loss)Step 0 → 12Both panels adapt scale to current trajectory.
2. Work with the current inputs
∇L=[u,4v],ut+1=(1−0.15)ut,vt+1=(1−4×0.15)vt\nabla L=[u,4v],\quad u_{t+1}=(1-0.15)u_t,\quad v_{t+1}=(1-4\times0.15)v_t
Lt=12(ut2+4vt2),t=12,Lt=9.10×10−2L_t=\frac12(u_t^2+4v_t^2),\quad t=12,\quad L_t=9.10\times10^{-2}
3. Result
Current loss0.09105
Current u / v0.427 / 0.000
Stable step rangeInside 0 < η < 0.5
Exact gradient updates on L(u,v)=(u²+4v²)/2 from (3,2). This convex loss has Hessian eigenvalues 1 and 4; convergence requires 0<η<0.5. The drawing rescales to show divergence, while the right plot uses log₁₀(1+loss). No minibatch noise or deep-network landscape is simulated.
References for this section3

Step-by-Step Training Loop

  1. Initialize parameters: Start with random or small values.
  2. Make predictions: Use the current model to predict outputs.
  3. Compute loss: Compare predictions with true values.
  4. Compute gradients: Measure how each parameter contributed to the loss.
  5. Update parameters: Move each parameter in the direction that lowers loss.
  6. Repeat: Continue until the loss stops improving or the maximum number of iterations is reached.
References for this section3

Learning Rate

The learning rate controls the step size. It is one of the most important hyperparameters in ML.

References for this section3

If the Learning Rate is Too Small

Training is stable, but very slow. The model may need thousands or millions of updates to reach a useful solution.

References for this section3

If the Learning Rate is Too Large

The model may jump over the minimum again and again. Loss can oscillate or even explode.

References for this section3

If the Learning Rate is Reasonable

The model moves quickly at first and then settles near a good minimum.

In real training, the best learning rate often changes over time. Many deep learning systems use learning-rate schedules, warmup, decay, or adaptive optimizers.

References for this section3

Batch, Stochastic, and Mini-Batch Gradient Descent

Batch size: few careful steps or many noisy ones?

1. Formula and symbols
L(w,b)=12n∑i=1n(wxi+b−yi)2L(w,b)=\frac1{2n}\sum_{i=1}^{n}(wx_i+b-y_i)^2
θ←θ−η 1B∑i∈B∇ℓi(θ),updates per epoch=⌈nB⌉\theta\leftarrow\theta-\eta\,\frac1B\sum_{i\in\mathcal B}\nabla\ell_i(\theta),\qquad\text{updates per epoch}=\Big\lceil\frac nB\Big\rceil
  • θ=(w,b)\theta=(w,b): Model parameters (slope and intercept)
  • nn: Training examples (32)
  • BB: Batch size: examples averaged per update
  • B\mathcal B: The batch drawn for this update (shuffled each epoch)
  • ℓi\ell_i: Loss on example i alone
  • η\eta: Learning rate (0.2 for every batch size here)

B = 1 is stochastic gradient descent, B = n is batch gradient descent, anything between is mini-batch.

startslope wbOne epoch = one pass over 32 pointsB = 132 updatesB = 48 updatesB = 84 updatesB = 321 updatesorange path: your batch sizegrey dashes: full batch · teal ✚: minimum
Batch size B
2. Work with the current inputs
updates=3×⌈324⌉=24\text{updates}=3\times\Big\lceil\frac{32}{4}\Big\rceil=24
(w,b)=(1.432, 1.093),L=0.1736,Lmin⁡=0.1018(w,b)=(1.432,\ 1.093),\quad L=0.1736,\quad L_{\min}=0.1018
3. Result
Parameter updates24full batch: 3
Loss now0.1736minimum 0.1018
Fitting y = wx + b to 32 points. Contours show the full-data loss; the cross marks the best (w, b). Full-batch descent (grey) takes one accurate step per epoch. Smaller batches take many more, noisier steps in the same epoch, so they move further for the same amount of data, but jitter around the minimum. Mini-batches balance the two and suit GPU hardware.
References for this section3

Batch Gradient Descent

Batch gradient descent uses the entire training dataset before making one update.

Advantages:

  • Stable gradient estimate.
  • Good for small datasets.

Disadvantages:

  • Very slow for large datasets.
  • Requires loading all data for each update.
References for this section3

Stochastic Gradient Descent

Stochastic gradient descent (SGD) updates the model using one training example at a time.

Advantages:

  • Fast updates.
  • Can escape shallow local minima due to noisy updates.

Disadvantages:

  • Noisy learning path.
  • Loss may fluctuate strongly.
References for this section3

Mini-Batch Gradient Descent

Mini-batch gradient descent uses a small batch, such as 16, 32, 64, or 128 examples, before each update. This is the common choice in modern deep learning.

Advantages:

  • More stable than SGD.
  • Faster than full batch training.
  • Works efficiently on GPUs.
References for this section3

Why Gradients Matter in Deep Learning

Deep learning models may have millions or billions of parameters. Manually adjusting them is impossible. Gradients provide an automatic way to know how each parameter should change.

The backpropagation algorithm efficiently computes these gradients layer by layer. Rumelhart, Hinton, and Williams popularized backpropagation for neural networks in their 1986 Nature paper.

References for this section3

Common Problems

References for this section3

Local Minima

  • Convex loss: may have one global minimum.
  • Deep-network loss: can include flat regions, saddle points, and poorly scaled directions.
  • Practical issue: an optimizer may progress slowly even without being trapped in a simple local minimum.

Stuck in a local minimum? Momentum can roll over the hill

1. Formula and symbols
L(w)=0.1w4−w2+0.6w+3L(w)=0.1w^4-w^2+0.6w+3
vt+1=βvt−ηL′(wt),wt+1=wt+vt+1v_{t+1}=\beta v_t-\eta L'(w_t),\qquad w_{t+1}=w_t+v_{t+1}
  • ww: Model parameter (the ball’s position)
  • L(w)L(w): Loss: a shallow local valley on the right, the deeper global valley on the left
  • L′(w)L'(w): Slope of the loss, 0.4w³ − 2w + 0.6
  • vv: Velocity: the accumulated update
  • η\eta: Learning rate
  • β\beta: Momentum: fraction of the previous velocity kept (β = 0 is plain gradient descent)

Momentum lets the update carry speed over a small hill. It is not a guarantee: with other settings it can also overshoot the good valley. Real deep-learning losses have many dimensions, where saddle points matter more than isolated local minima.

−3030510parameter wloss L(w)globallocalhillupdate 0 of 160 · velocity 0.00
2. Work with the current inputs
w0=3.200,v0=0.000,L=5.166w_{0}=3.200,\quad v_{0}=0.000,\quad L=5.166
after 160 updates: w=2.067, L=1.793\text{after 160 updates: }w=2.067,\ L=1.793
3. Result
Ends inLocal minimumlocal minimum (w ≈ 2.07)
Final loss1.793global minimum ≈ −0.89
The ball starts on the right slope and follows gradient descent. With no momentum it settles in the nearest, shallow valley. Give it momentum (β ≈ 0.9) and the stored velocity carries it over the hump into the deeper valley on the left. The animation replays the 160 updates; the slider lets you step through them.
References for this section3

Vanishing Gradients

In deep networks, gradients can become extremely small as they move backward through layers. Early layers then learn very slowly. Activation functions, normalization, residual connections, and better initialization help reduce this problem.

References for this section3

Exploding Gradients

Gradients can also become too large, causing unstable updates. Gradient clipping is a common solution, especially in recurrent neural networks.

References for this section3

Overfitting

Gradient descent can reduce training loss while the model becomes worse on new data. Regularization, dropout, early stopping, and validation monitoring help prevent this.

References for this section3

Python: Gradient Descent Through scikit-learn

You normally do not write gradient descent manually for classical ML. You choose a model that uses it internally. SGDClassifier and SGDRegressor are useful when the dataset is large or arrives in batches.

from sklearn.datasets import make_classification
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score

X, y = make_classification(
    n_samples=2000,
    n_features=20,
    n_informative=8,
    random_state=42
)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

model = make_pipeline(
    StandardScaler(),
    SGDClassifier(loss="log_loss", learning_rate="optimal", random_state=42)
)

model.fit(X_train, y_train)
print("Accuracy:", accuracy_score(y_test, model.predict(X_test)))
References for this section3

Python: Manual Gradient Descent for Linear Regression

This tiny example shows the update rule directly. It is not meant to replace libraries, but it makes the mechanics visible.

import numpy as np

rng = np.random.default_rng(42)
X = rng.normal(size=(100, 1))
y = 3 * X[:, 0] + 2 + rng.normal(scale=0.2, size=100)

w = 0.0
b = 0.0
alpha = 0.05

for epoch in range(500):
    y_hat = w * X[:, 0] + b
    error = y_hat - y

    dw = (2 / len(X)) * np.sum(error * X[:, 0])
    db = (2 / len(X)) * np.sum(error)

    w -= alpha * dw
    b -= alpha * db

print("learned weight:", round(w, 2))
print("learned bias:", round(b, 2))
References for this section3

Practical Checklist

  • Normalize or standardize features before training.
  • Start with a reasonable learning rate and monitor the loss curve.
  • If loss explodes, reduce the learning rate.
  • If loss decreases too slowly, try a larger learning rate or an adaptive optimizer.
  • Use a validation set to detect overfitting.
  • For neural networks, try Adam or AdamW first, then tune.
References for this section3

Takeaway

  • Core question: which parameter change reduces loss locally?
  • Learning rate: step size.
  • Optimizer: rule that shapes or adapts the steps.

Continue with Classification Algorithms to build on this note.

References for this section3

Check your understanding

0 of 4 answered

  1. For w=3, gradient=2 and learning rate 0.1, what is the next w?

  2. For L=(u²+4v²)/2, what is its gradient at (3,2)?

  3. In the lab, the v update multiplies v by 1−4η. What happens at η=0.6?

  4. What does backpropagation compute?

Complete references and further reading