Skip to content

AIPrimer A04Before Day 9

Derivatives and Basic Probability

8 min read · outside the 100 days

Training a model means walking downhill on its loss, so you need to know which way is down. Many models also answer with a chance, not a number. This primer covers the slopes and the probability the course uses, and nothing more.

Read before: Day 9 · about 20 minutes

A derivative is a slope

The derivative of a function at a point is its slope there. It says how fast the output moves when the input moves by a tiny amount. You can measure it by nudging: move the input a little, and divide the change in the output by the size of the nudge.

Take the loss L=(w−2)2L = (w - 2)^2 at w=0w = 0, where L=4L = 4. Nudge ww to 0.001, and LL becomes (−1.999)2=3.996001(-1.999)^2 = 3.996001. The loss fell by 0.004 for a nudge of 0.001, so the slope is about −4.

The sign is the useful part. A negative slope means the loss falls as ww grows, so step right. A positive slope means step left. At the bottom, the slope is 0. Gradient descent reads this sign and size at every step.

A model has many weights. The partial derivative ∂L∂w\frac{\partial L}{\partial w} is the slope when only ww moves and every other weight stays put. All of them together form the gradient.

You rarely nudge by hand, because a few rules give slopes exactly:

Function Its slope
a constant, such as 7 0
awa w, such as 3w3w aa
w2w^2 2w2w
(w−c)2(w - c)^2 2(w−c)2(w - c)
ReLU(z)\text{ReLU}(z), which turns negatives into 0 1 when z>0z > 0, else 0

This checks the rule 2(w−2)2(w - 2) against the nudge at four points:

# script_id: primer_a04/slopes
def slope(f, w, eps=1e-3):
    """Nudge w a tiny step each way and see how fast f moves."""
    return (f(w + eps) - f(w - eps)) / (2 * eps)


def loss(w):
    return (w - 2) ** 2


for w in [0, 1, 2, 3]:
    print(f"w = {w}:  loss {loss(w)},  nudged slope {slope(loss, w):+.3f},  rule 2(w - 2) = {2 * (w - 2):+d}")
w = 0:  loss 4,  nudged slope -4.000,  rule 2(w - 2) = -4
w = 1:  loss 1,  nudged slope -2.000,  rule 2(w - 2) = -2
w = 2:  loss 0,  nudged slope +0.000,  rule 2(w - 2) = +0
w = 3:  loss 1,  nudged slope +2.000,  rule 2(w - 2) = +2

The chain rule

A network is a chain: a weight sets a hidden value, and the hidden value sets the loss. The chain rule says the slope of the whole chain is the product of the slopes of its links.

Take h=3wh = 3w, then L=(h−4)2L = (h - 4)^2, at w=2w = 2. So h=6h = 6.

  • How LL moves with hh: 2(h−4)=2(6−4)=42(h - 4) = 2(6 - 4) = 4.
  • How hh moves with ww: 3.
  • How LL moves with ww: 4×3=124 \times 3 = 12.

It makes sense: if ww moves by 0.001, hh moves 3 times as far, and LL moves 4 times as far as hh. The nudge agrees:

# script_id: primer_a04/slopes
def h(w):
    return 3 * w                  # link 1: slope 3


def L(h):
    return (h - 4) ** 2           # link 2: slope 2(h - 4)


w = 2
print(f"chain rule: 2({h(w)} - 4) × 3 = {2 * (h(w) - 4) * 3}")
print(f"nudge test: {slope(lambda w: L(h(w)), w):.3f}")
chain rule: 2(6 - 4) × 3 = 12
nudge test: 12.000

Backpropagation is this rule run along every link of a network, from the loss back to each weight.

Probability as a share

A probability is a number from 0 (never) to 1 (always). From data, it's usually a share: the count of times something happened, divided by the count of chances. The chance it doesn't happen is 1−P1 - P.

The bike-share data has 17,379 hours. Call an hour busy if it had over 300 rentals: 3,891 were, so P(busy)=3891/17379≈0.224P(\text{busy}) = 3891 / 17379 \approx 0.224.

A conditional probability P(A∣B)P(A \mid B), read "A given B", counts only the rows where B is true. Of the 1,422 hours with rain or snow ("wet"), 129 were busy. So P(busy∣wet)=129/1422≈0.091P(\text{busy} \mid \text{wet}) = 129 / 1422 \approx 0.091. Rain cuts the chance of a busy hour by more than half.

Two events are independent when knowing one tells you nothing about the other. Then the chance of both is the product: P(A and B)=P(A)×P(B)P(A \text{ and } B) = P(A) \times P(B). Here the product predicts far more busy, wet hours than really happened, so busy and wet aren't independent:

# script_id: primer_a04/bike
import os
from pathlib import Path

import pandas as pd

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
busy = df["cnt"] > 300                         # True for a busy hour
wet = df["weathersit"] >= 3                    # rain or snow
print(f"P(busy)          = {busy.mean():.3f}")
print(f"P(busy | wet)    = {busy[wet].mean():.3f}")
print(f"P(busy and wet)  = {(busy & wet).mean():.4f}")
print(f"P(busy) × P(wet) = {busy.mean() * wet.mean():.4f}")
P(busy)          = 0.224
P(busy | wet)    = 0.091
P(busy and wet)  = 0.0074
P(busy) × P(wet) = 0.0183

e and ln

The number ee is about 2.718. It turns up in the sigmoid, the S-curve that turns a score into a chance, 11+e−z\frac{1}{1 + e^{-z}}, and in the bell curve below. The natural log ln⁡\ln undoes it: ln⁡(ex)=x\ln(e^x) = x.

Two facts about ln⁡\ln carry most of the course:

  1. The log of a chance is never above 0. ln⁡1=0\ln 1 = 0, and ln⁡p\ln p sinks as pp shrinks toward 0. So −ln⁡p-\ln p is a penalty that is small for a confident right answer and huge for a confident wrong one. That's log loss.
  2. Logs turn products into sums: ln⁡(ab)=ln⁡a+ln⁡b\ln(ab) = \ln a + \ln b. Multiply 200 chances of 0.01 and a computer rounds the answer to 0. Add their logs instead, and the number stays usable.
# script_id: primer_a04/logs
import numpy as np

p = np.full(200, 0.01)                         # 200 words, each with a chance of 0.01
print("product:     ", np.prod(p))             # 1e-400 is too small for a float
print("sum of logs: ", np.log(p).sum().round(2))
print("-ln p for p = 0.95, 0.5, 0.05:", (-np.log([0.95, 0.5, 0.05])).round(2).tolist())
product:      0.0
sum of logs:  -921.03
-ln p for p = 0.95, 0.5, 0.05: [0.05, 0.69, 3.0]

The bell curve

Some values, such as heights or the time a bus arrives, cluster around a middle and thin out both ways. The Gaussian (or normal) curve describes them:

p(x)=1σ2π e−(x−μ)22σ2p(x) = \frac{1}{\sigma\sqrt{2\pi}}\, e^{-\frac{(x - \mu)^2}{2\sigma^2}}
Symbol Meaning
μ\mu the mean: the centre of the bell
σ\sigma the standard deviation: how wide the bell is
p(x)p(x) the density: the height of the curve at xx

Worked: at the centre of a bell with μ=0\mu = 0 and σ=1\sigma = 1, the ee part is e0=1e^0 = 1, so p(0)=12π≈0.399p(0) = \frac{1}{\sqrt{2\pi}} \approx 0.399.

A density is not a probability. A taller curve means more typical, but a narrow bell can rise above 1. The probability of landing in a range is the area under the curve there, and the whole area is 1.

# script_id: primer_a04/bell
import numpy as np


def density(x, mu, sigma):
    return np.exp(-((x - mu) ** 2) / (2 * sigma**2)) / (sigma * np.sqrt(2 * np.pi))


print("heights at 0, 1, 2:", density(np.array([0, 1, 2]), mu=0, sigma=1).round(3))
print("narrow bell at 0:  ", density(0, mu=0, sigma=0.1).round(2))
xs = np.linspace(-1, 1, 20_001)
print(f"area from -1 to 1:  {np.trapezoid(density(xs, 0, 1), xs):.3f}")
heights at 0, 1, 2: [0.399 0.242 0.054]
narrow bell at 0:   3.99
area from -1 to 1:  0.683

About 68% of the values land within one standard deviation of the mean.

Quick check

Quick check

1. At w = 5, the slope of the loss is +3. Which way should w move to lower the loss?

2. h = 2w, and L moves with h at a rate of 5. How fast does L move with w?

3. Of 50 texts containing 'prize', 40 are spam. What is P(spam | prize)?

Next

Slopes drive Day 9 and Day 30, and chances, logs and bells drive Day 12, Day 18 and Day 21.

Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.