Machine Learning · Optimization · Step-by-Step Mathematics

Gradient Descent:
The Math Behind How AI Learns

Loss functions, derivatives, update rule, learning rate — explained with full numeric examples

Author: M. Nagesh
Institution: KL University
Domain: AI / Machine Learning

Every time a neural network trains — every time ChatGPT got smarter — Gradient Descent was quietly doing all the work. Let's understand exactly how, with real numbers at every step.

📋 Topics Covered
  1. What is a Loss Function?
  2. What is Gradient Descent?
  3. The Intuition — Foggy Hill Analogy
  4. The Math — Derivative & Update Rule
  5. Step-by-Step Numeric Example (5 Iterations)
  6. Multiple Parameters & Partial Derivatives
  7. The Role of Learning Rate
  8. Types of Gradient Descent
  9. Gradient Descent in Python

Gradient Descent = A simple way to slide down the error curve step by step until we reach the lowest point — that lowest point is where the model has learned.


CONCEPT 01 What is a Loss Function?

Before gradient descent can do anything, it needs something to minimize. A loss function is that thing — it measures how wrong the model's prediction is. The bigger the loss, the worse the model.

🇬🇧 EnglishLoss = how far the model's prediction is from the actual value.
🇮🇳 TeluguLoss = model prediction అసలు value నుండి ఎంత దూరంలో ఉందో.
🇮🇳 HindiLoss = model की prediction असली value से कितनी दूर है।
House Price Example — Computing MSE Step by Step

Why square the error?

Squaring makes all errors positive — negative and positive errors won't cancel out.

📈
Why not use |Error|?

Squaring penalizes large errors much more — it forces the model to fix big mistakes first.

Our Goal: Make the loss as small as possible. This is exactly what Gradient Descent does.

CONCEPT 02 What is Gradient Descent?

📐
Gradient

The slope or steepness of the loss function at any given point. It tells us which direction is uphill and by how much.

⬇️
Descent

Going downward — moving in the direction that reduces the loss, step by step, toward the minimum.

One-Line Definition
Gradient Descent = repeatedly adjust weights in the direction that reduces the loss, until the loss is minimized.

CONCEPT 03 The Intuition — Foggy Hill Analogy

⛰️ Foggy Hill Analogy

Imagine standing on a hill in thick fog. You cannot see the bottom of the valley — your goal. The only thing you can feel is the slope under your feet.

What do you do? Feel which direction the ground goes down and take a step that way. Steep slope → big step. Gentle slope → small step. Keep repeating until the ground is flat — you reached the bottom!

The Hill = Loss Function  |  The Valley = Minimum Loss  |  The Slope = Gradient  |  Each Step = Weight Update


CONCEPT 04 The Math — Derivative & Update Rule

Now let's translate the hill analogy into actual mathematics — step by step.

What is a Derivative? — The Slope of a Function

The Gradient Descent Update Rule
w_new = w_old − α × f'(w_old)
w_oldcurrent weight value
w_newupdated weight after one step
α (alpha)learning rate — controls step size (e.g. 0.1)
f'(w_old)gradient (slope) at the current weight
Why subtract the gradient? — The Beauty of the Minus Sign

STEP-BY-STEP 05 Full Numeric Example — 5 Iterations

Setup — Our Loss Function
ITERATION 1  —  w starts at 0
ITERATION 2  —  w = 0.6
ITERATION 3  —  w = 1.08

ALL 5 ITERATIONS — SUMMARY TABLE:

Step w (before) Gradient: 2(w−3) α × Gradient w_new Loss f(w_new)
10−6.000−0.6000.6005.760
20.600−4.800−0.4801.0803.686
31.080−3.840−0.3841.4642.359
41.464−3.072−0.3071.7711.510
51.771−2.458−0.2462.0170.966 ↓
Key Observation: w is getting closer to 3 with every step. The gradient is also shrinking — meaning steps get smaller as we approach the minimum. This is how gradient descent converges.

CONCEPT 06 Multiple Parameters & Partial Derivatives

📺 TV Knobs Analogy

Imagine a TV with two knobs — volume and brightness. To understand each knob's effect, you turn one at a time while keeping the other fixed.

A partial derivative does exactly this — it measures how loss changes with respect to one weight while all others stay fixed.

Two-Parameter Update — L(w1, w2)

CONCEPT 07 The Role of Learning Rate (α)

The learning rate controls step size. Too small = painfully slow. Too large = overshoots and diverges. Let's prove this with actual numbers.

⏳ α = 0.01 — Too Small
Step 1: grad=−6
w = 0+0.01×6 = 0.06
Step 2: grad=−5.88
w = 0.06+0.0588 = 0.119

After 20 steps: w ≈ 0.997
Still far from 3 ❌

Extremely slow convergence.
✅ α = 0.1 — Just Right
Step 1: w → 0.600
Step 2: w → 1.080
Step 3: w → 1.464
Step 4: w → 1.771
Step 5: w → 2.017

Step 50: w = 3.000 ✓

Smooth, steady convergence.
💥 α = 1.5 — Too Large
Step 1: grad=−6
w = 0+1.5×6 = 9 ❌ overshot!
Step 2: grad=2(9−3)=12
w = 9−1.5×12 = −9

0 → 9 → −9 → ...

Diverging — never converges.
Learning Rate Quick Reference
Too Small (0.001)Converges but extremely slowly.SLOW
Just Right (0.01–0.1)Smooth convergence to the minimum.IDEAL ✓
Too Large (1.5+)Overshoots minimum, bounces wildly, diverges.DIVERGES

In practice: start with 0.001 or 0.01. For large Transformer models: 1e-4 or smaller.


CONCEPT 08 Types of Gradient Descent

Type Data Per Step Speed Gradient Quality Best For
Batch GD Entire dataset Slow High (exact) Small datasets
SGD 1 random point Fast Noisy Online learning
Mini-Batch GD ⭐ Batch of 32–1024 Moderate Balanced Most real-world models
In Practice: Mini-Batch GD is used for almost all deep learning today. PyTorch's torch.optim.SGD is actually mini-batch SGD.

CODE 09 Gradient Descent in Python

Let's run the exact same math in Python — f(w) = (w−3)², starting from w=0, learning rate=0.1.

PYTHON
# Gradient Descent on f(w) = (w - 3)²
# Minimum is at w = 3 → loss = 0

w = 0.0 # starting weight
learning_rate = 0.1 # alpha (α)

for step in range(50):
    # Step 1: compute gradient → f'(w) = 2(w - 3)
    gradient = 2 * (w - 3)

    # Step 2: update rule → w = w - α × gradient
    w = w - learning_rate * gradient

    # Step 3: compute new loss → f(w) = (w - 3)²
    loss = (w - 3) ** 2

    print(f"Step {step+1:>2}: w = {w:.4f} loss = {loss:.6f}")
Output — Selected Steps

After 50 steps, w = 3 exactly and loss = 0. In real deep learning frameworks like PyTorch and TensorFlow, gradients are computed automatically via backpropagation — the same update rule applies.


FINAL Putting It All Together

🎯 Key Takeaways
THE CORE FORMULA — NEVER FORGET
w_new = w_old − α × f'(w_old)
This one line is how every neural network — GPT, BERT, ResNet — actually learns.
#GradientDescent #MachineLearning #DeepLearning #Optimization #LossFunction #NeuralNetworks #Mathematics #Python #DataScience #KLUniversity