SECTION 03 / 4

Gradient Descent — Learning by Walking Downhill

7 min read
On this page 10 headings
BUILD INTUITION WITH NUMBERS

One complete sigmoid learning step

One example: input 2, target 1. Start with weight 0.5 and bias −1. Use loss ½(prediction − target)² and learning rate 0.5.

  1. Forward pass: find the current prediction.

    z=0.5(2)−1=0,f=σ(0)=0.5z=0.5(2)-1=0,\qquad f=\sigma(0)=0.5
  2. Differentiate the chosen loss.

    ∂L∂w=(f−y)f(1−f)x=(−0.5)(0.5)(0.5)(2)=−0.25\begin{aligned}\frac{\partial L}{\partial w}&=(f-y)f(1-f)x\\&=(-0.5)(0.5)(0.5)(2)\\&=-0.25\end{aligned}
  3. The bias has the same derivative, without the input factor.

    ∂L∂b=(−0.5)(0.5)(0.5)=−0.125\frac{\partial L}{\partial b}=(-0.5)(0.5)(0.5)=-0.125
  4. Subtract the learning rate times each gradient.

    wnew=0.5−0.5(−0.25)=0.625bnew=−1−0.5(−0.125)=−0.9375\begin{aligned}w_{new}&=0.5-0.5(-0.25)=0.625\\b_{new}&=-1-0.5(-0.125)=-0.9375\end{aligned}
  5. Check that the prediction moved toward the target.

    znew=0.3125,σ(znew)≈0.5775z_{new}=0.3125,\qquad\sigma(z_{new})\approx0.5775

What changed? Negative gradients make these parameters increase. The new prediction is closer to the target of 1.

Quick check: Why does subtracting a negative gradient increase a parameter?

Because −η(−g) = +ηg when η and g are positive.

Swipe long formulas, tables or code sideways to see the rest.

Start here Imagine you are on a foggy hill and want to reach the valley. You can’t see far, but you can feel which way the ground slopes under your feet. So you take a small step downhill, feel again, and repeat. That is gradient descent. This page shows why “downhill” means “opposite to the gradient”, using a short Taylor-series argument, and then works it out for the sigmoid neuron.

1. The goal

Find a better way to move on the error surface, so we reach the minimum quickly, without brute-force search.

2. Setting up a step

Put all parameters in one vector: θ=[w,b]\theta = [w, b] (start randomly).

We will move by a small change Δθ=[Δw,Δb]\Delta \theta = [\Delta w, \Delta b]. To be careful, we move only a small amount η\eta (eta, the learning rate) in that direction:

θnew=θ+η⋅Δθ\theta _{\mathrm{new}} = \theta + \eta \cdot \Delta \theta

The question: what is the right Δθ\Delta \theta ? The answer comes from the Taylor series.

3. Taylor series in one minute

A Taylor series approximates a smooth function L(w) near a point w0w_{0} using polynomials. Higher degree → better approximation.

L(w)=L(w0)+L′(w0)/1!⋅(w−w0)+L′′(w0)/2!⋅(w−w0)2+L′′′(w0)/3!⋅(w−w0)3+…L(w) = L(w_{0}) + L'(w_{0})/1! \cdot (w - w_{0}) + L''(w_{0})/2! \cdot (w - w_{0})^{2} + L'''(w_{0})/3! \cdot (w - w_{0})^{3} + \ldots

  • Linear approximation (degree 1):L(w)≈L(w0)+L′(w0)(w−w0) L(w) \approx L(w_{0}) + L'(w_{0})(w - w_{0})
  • Quadratic approximation (degree 2): add the L″ term.

Close to w0w_{0}, even the straight-line approximation is very good.

Everyday example On a small patch of a curved road, the road looks straight. The smaller the patch, the better a straight line fits it.

4. Which direction makes the loss go down?

Write Δθ=\Delta \theta = u. From the Taylor series (for many variables):

L(θ+ηu)=L(θ)+η⋅uT∇θL(θ)+(η2/2!)⋅uT∇2L(θ)u+…L(\theta + \eta u) = L(\theta ) + \eta \cdot u^{T}\nabla \theta L(\theta ) + (\eta ^{2}/2!) \cdot u^{T}\nabla ^{2}L(\theta )u + \ldots

η\eta is small, so η2,η3,…\eta ^{2}, \eta ^{3}, \ldots are tiny and can be dropped:

L(θ+ηu)≈L(θ)+η⋅uT∇θL(θ)L(\theta + \eta u) \approx L(\theta ) + \eta \cdot u^{T}\nabla \theta L(\theta )

The move is good only if the new loss is smaller: L(θ+ηu)−L(θ)<0L(\theta + \eta u) - L(\theta ) < 0, which means

uT∇θL(θ)<0u^{T}\nabla \theta L(\theta ) < 0

How negative can it be? LetβLet \beta be the angle between u and ∇θL(θ)\nabla \theta L(\theta ):

−1≤cos⁡β=uT∇θL(θ)/(∥u∥⋅∥∇θL(θ)∥)≤1-1 \le \cos \beta = u^{T}\nabla \theta L(\theta ) / (\Vert u\Vert \cdot \Vert \nabla \theta L(\theta )\Vert ) \le 1

Multiply by k=∥u∥⋅∥∇θL(θ)∥k = \Vert u\Vert \cdot \Vert \nabla \theta L(\theta )\Vert :

−k≤kcos⁡β=uT∇θL(θ)≤k-k \le k \cos \beta = u^{T}\nabla \theta L(\theta ) \le k

The change in loss is most negative when cos⁡β=−1,i\cos \beta = -1, i.e. β=180∘\beta = 180{}^\circ .

The gradient points uphill. Stepping at 180° to it is the fastest way down.
The gradient points uphill. Stepping at 180° to it is the fastest way down.
Open image ↗
A walker on a hill steps in the direction opposite to the uphill gradient arrow

5. The gradient descent rule

Move opposite to the gradient:

  • wt+1=wt−η∇wtw_{t+1} = w_t - \eta \nabla w_t
  • bt+1=bt−η∇btb_{t+1} = b_t - \eta \nabla b_t

where ∇wt=∂L(w,b)/∂w\nabla w_t = \partial L(w, b)/\partial w and ∇bt=∂L(w,b)/∂b\nabla b_t = \partial L(w, b)/\partial b, both evaluated at w=wt,b=btw = w_t, b = b_t.

t ← 0;  max_iterations ← 1000
w, b ← random
while t < max_iterations:
    w ← w − η ∇w
    b ← b − η ∇b
    t ← t + 1

Now we need ∇w\nabla w and ∇b\nabla b for our sigmoid neuron.

6. Deriving ∇w and ∇b for the sigmoid neuron

Model: f(x)=11+e−(wx+b)f(x) = \frac{1}{1 + e^{-(wx + b)}}. Take one point (x, y) and loss L=12(f(x)−y)2L = \frac{1}{2} (f(x) - y)^{2}. (The ½ makes the 2 from the square cancel.)

Step 1 — outer part (chain rule):

∇w=∂/∂w[12(f(x)−y)2]=12⋅2(f(x)−y)⋅∂/∂w(f(x)−y)=(f(x)−y)⋅∂f(x)/∂w\nabla w = \partial /\partial w [\frac{1}{2} (f(x) - y)^{2}] = \frac{1}{2} \cdot 2 (f(x) - y) \cdot \partial /\partial w (f(x) - y) = (f(x) - y) \cdot \partial f(x)/\partial w

Step 2 — derivative of the sigmoid with respect to w:

∂/∂w[11+e−(wx+b)]=−11+e−(wx+b)2⋅∂/∂w[e−(wx+b)]=−11+e−(wx+b)2⋅e−(wx+b)⋅∂/∂w[−(wx+b)]=−11+e−(wx+b)2⋅e−(wx+b)⋅(−x)=[11+e−(wx+b)]⋅[e−(wx+b)/(1+e−(wx+b))]⋅x=\partial /\partial w [\frac{1}{1 + e^{-(wx+b)}}] = -\frac{1}{1 + e^{-(wx+b)}}^{2} \cdot \partial /\partial w [e^{-(wx+b)}] = -\frac{1}{1 + e^{-(wx+b)}}^{2} \cdot e^{-(wx+b)} \cdot \partial /\partial w [-(wx + b)] = -\frac{1}{1 + e^{-(wx+b)}}^{2} \cdot e^{-(wx+b)} \cdot (-x) = [\frac{1}{1 + e^{-(wx+b)}}] \cdot [e^{-(wx+b)}/(1 + e^{-(wx+b)})] \cdot x = f(x) · (1 − f(x)) · x

(because e−z/(1+e−z)=1−11+e−z=1−f(x)e^{-z}/(1 + e^{-z}) = 1 - \frac{1}{1 + e^{-z}} = 1 - f(x).)

Result for one point:

  • ∇w=(f(x)−y)⋅f(x)⋅(1−f(x))⋅x\nabla w = (f(x) - y) \cdot f(x) \cdot (1 - f(x)) \cdot x
  • ∇b=(f(x)−y)⋅f(x)⋅(1−f(x))\nabla b = (f(x) - y) \cdot f(x) \cdot (1 - f(x)) (same, but ∂(wx+b)/∂b=1\partial (wx + b)/\partial b = 1 instead of x)

For two (or N) points, add them up:

∇w=∑i(f(xi)−yi)⋅f(xi)⋅(1−f(xi))⋅xi∇b=∑i(f(xi)−yi)⋅f(xi)⋅(1−f(xi))\nabla w = \sum _{i} (f(x_{i}) - y_{i}) \cdot f(x_{i}) \cdot (1 - f(x_{i})) \cdot x_{i} \nabla b = \sum _{i} (f(x_{i}) - y_{i}) \cdot f(x_{i}) \cdot (1 - f(x_{i}))

7. The code from the lecture

import numpy as np
X = [0.5, 2.5]
Y = [0.2, 0.9]

def f(x, w, b):            # sigmoid neuron
    return 1 / (1 + np.exp(-(w*x + b)))

def error(w, b):           # loss = 0.5 * sum of squared errors
    err = 0.0
    for x, y in zip(X, Y):
        fx = f(x, w, b)
        err += (fx - y) ** 2
    return 0.5 * err

def grad_b(x, w, b, y):
    fx = f(x, w, b)
    return (fx - y) * fx * (1 - fx)

def grad_w(x, w, b, y):
    fx = f(x, w, b)
    return (fx - y) * fx * (1 - fx) * x

def do_gradient_descent():
    w, b, eta, max_epochs = -2, -2, 1.0, 1000
    for i in range(max_epochs):
        dw, db = 0, 0
        for x, y in zip(X, Y):
            dw += grad_w(x, w, b, y)
            db += grad_b(x, w, b, y)
        w = w - eta * dw
        b = b - eta * db

8. One step by hand (start w = −2, b = −2, η = 1)

Point wx+bwx + b f(x) f−yf - y f(1 − f) grad_w term grad_b term
(0.5, 0.2) −2(0.5)−2=−3-2(0.5) - 2 = -3 σ(−3)=0.0474\sigma (-3) = 0.0474 −0.1526 0.0452 −0.003446 −0.006893
(2.5, 0.9) −2(2.5)−2=−7-2(2.5) - 2 = -7 σ(−7)=0.000911\sigma (-7) = 0.000911 −0.8991 0.000910 −0.002046 −0.000818
  • ∇w=−0.003446+(−0.002046)=\nabla w = -0.003446 + (-0.002046) = −0.005492
  • ∇b=−0.006893+(−0.000818)=\nabla b = -0.006893 + (-0.000818) = −0.007711
  • wnew=−2−1×(−0.005492)=w_{\mathrm{new}} = -2 - 1 \times (-0.005492) = −1.99451
  • bnew=−2−1×(−0.007711)=b_{\mathrm{new}} = -2 - 1 \times (-0.007711) = −1.99229

The loss goes from 0.41581 to 0.41573 — a very small improvement, because the starting point is on a flat part of the surface (tiny gradients).

Lecture example — running it Running the full loop (computed in code): loss after 10 steps ≈0.4148\approx 0.4148 (still flat), after 100 steps ≈0.0177\approx 0.0177, after 1000 steps ≈0\approx 0 with w≈1.792,b≈−2.282w \approx 1.792, b \approx -2.282 — the exact best answer. Slow at first on the flat region, then fast.

Later in the course we study gradient descent and its variants in much more detail (Week 4). For now we have an algorithm to learn the parameters of a sigmoid neuron.

In one line: Gradient descent repeatedly moves the parameters a small step η\eta opposite to the gradient, because that direction reduces the loss fastest.

Exam words: gradient descent, learning rate η\eta , Taylor series, linear approximation, gradient ∇θL\nabla \theta L, angle β=180∘\beta = 180{}^\circ , update rule, ∇w=(f−y)f(1−f)x,∇b=(f−y)f(1−f)\nabla w = (f - y) f (1 - f) x, \nabla b = (f - y) f (1 - f), epoch.

Quick check

  1. Why do we drop the η2\eta ^{2} term in the Taylor series?
η\eta is small, so η2,η3,…\eta ^{2}, \eta ^{3}, \ldots are much smaller and can be ignored. Only the first-order term remains.
  1. ∇w=0.3,w=1,η=0.1\nabla w = 0.3, w = 1, \eta = 0.1. New w?
w=1−0.1×0.3=0.97. w = 1 - 0.1 \times 0.3 = 0.97.
  1. One point x=1,y=1,w=0,b=0x = 1, y = 1, w = 0, b = 0. Compute ∇w\nabla w.
f=σ(0)=0.5.∇w=(0.5−1)×0.5×0.5×1=−0.125. f = \sigma (0) = 0.5. \nabla w = (0.5 - 1) \times 0.5 \times 0.5 \times 1 = -0.125.
  1. In which direction should u point relative to the gradient?
Exactly opposite (β=180∘)(\beta = 180{}^\circ ), so cos⁡β=−1\cos \beta = -1 and the loss drops the most.
  1. Why was progress so slow in the first few steps from (−2, −2)?
Both points give f(x) near 0, where the sigmoid is flat: f(1 − f) is tiny, so the gradient is tiny and the steps are tiny.
YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑