AIPrimer A04Before Day 9
Derivatives and Basic Probability
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 at , where . Nudge to 0.001, and becomes . 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 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 is the slope when only 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 |
| , such as | |
| , which turns negatives into 0 | 1 when , else 0 |
This checks the rule 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 , then , at . So .
- How moves with : .
- How moves with : 3.
- How moves with : .
It makes sense: if moves by 0.001, moves 3 times as far, and moves 4 times as far as . 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.
e and ln
The number is about 2.718. It turns up in the sigmoid, the S-curve that turns a score into a chance, , and in the bell curve below. The natural log undoes it: .
Two facts about carry most of the course:
- The log of a chance is never above 0. , and sinks as shrinks toward 0. So is a penalty that is small for a confident right answer and huge for a confident wrong one. That's log loss.
- Logs turn products into sums: . 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:
| Symbol | Meaning |
|---|---|
| the mean: the centre of the bell | |
| the standard deviation: how wide the bell is | |
| the density: the height of the curve at |
Worked: at the centre of a bell with and , the part is , so .
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.