Workshop: Implementing Gradient Descent from Scratch
Learning objectives
- Load the book's learning set in Python and write full-batch gradient descent from scratch for porosity on density
- Find the learning rate's limit from the Hessian's eigenvalues, and see why standardizing density lets the descent finish
- Write stochastic and mini-batch gradient descent with the book's seeded order, and replay a run to the last digit
- Show that an epoch's mini-batch gradients average to the full gradient, and read the noise a small batch adds
A Batch at a Time
Stochastic gradient descent steps on the gradient of one sample, mini-batch descent on that of a few, each in an order a seeded shuffle sets anew every epoch. A batch's gradient is the full gradient plus noise, and over an epoch's batches its mean is the full gradient exactly. On Section 3.1's fit, porosity on standardized density in Ogbon-1's sandstone at a rate of 0.03, mini-batches of 8 take 770 steps in 10 epochs and end at β0.530 v/v per g/cc, about least squares' β0.520; the full batch takes 10 steps and ends at β0.240. One sample at a time takes 6160 steps and ends at β0.542, wandering about the answer: a constant rate leaves the noise in.
The Data
The workshop reads the book's own learning set as a CSV file, mlgeo-core/data/ogbon-learning-set.csv on this site, and keeps Ogbon-1's 616 samples of sandstone: density as the book's own tool model records it, porosity the generator's truth. The set is synthetic, and that is why every number below can be checked. The file holds density and porosity to four decimals, so a last printed digit can differ from the kernel's, which works on the full numbers.
Each step below gives its code and then what the book's kernel gives for the same computation on the same samples.
Step 1: Load the Sandstone
One Row per Half Foot
The file's comment lines name the source and each column's unit; pandas skips them.
import numpy as np
import pandas as pd
URL = "https://ogbonlab.com/mlgeo-core/data/ogbon-learning-set.csv"
df = pd.read_csv(URL, comment="#")
sand = df[(df["well"] == "Ogbon-1")
& (df["lith"] == "sandstone")]
x = sand["RHOB_gcc"].to_numpy()
y = sand["PHI_vv"].to_numpy()
n = len(x)
print(n)
The book's kernel gives 616 samples.
Step 2: The Answer
Least Squares
The line every descent below is walking to.
w_ls, b_ls = np.polyfit(x, y, 1)
print(w_ls, b_ls)
The book's kernel gives a slope of β0.520 v/v per g/cc and an intercept of 1.411 v/v.
Step 3: Full-Batch Descent in g/cc
The Step and Its Limit
The gradient of the mean squared error is , its Hessian , and the descent converges only below .
def descend(A, y, lr, epochs):
theta = np.zeros(A.shape[1])
for _ in range(epochs):
e = A @ theta - y
theta = theta - lr * 2 / len(y) * A.T @ e
return theta
A = np.column_stack([np.ones(n), x])
lam = np.linalg.eigvalsh(2 / n * A.T @ A)
limit = 2 / lam.max()
print(lam, limit)
b, w = descend(A, y, 0.95 * limit, 100)
print(w)
The book's kernel gives eigenvalues of 12.301 and 0.00136, a limit of 0.163, and after 100 epochs at 0.95 of it a slope of +0.073 v/v per g/cc: the flat direction has barely moved, as Section 3.1 showed.
Step 4: Standardize
One Step
Standardized, both eigenvalues are 2, the limit is 1, and half of it lands on the answer at once. The slope is written back on g/cc by dividing by density's standard deviation.
z = (x - x.mean()) / x.std()
Az = np.column_stack([np.ones(n), z])
b, wz = descend(Az, y, 0.5, 1)
print(wz / x.std())
The book's kernel gives β0.520 v/v per g/cc after one step.
Step 5: The Book's Seeded Order
A Shuffle You Can Replay
The kernel draws its random numbers from mulberry32, a small 32-bit generator, and shuffles from the top (Fisher and Yates). Written in Python it gives the kernel's orders exactly, so every run below is the figure's.
M32 = 0xFFFFFFFF
def mulberry32(seed):
s = seed & M32
def draw():
nonlocal s
s = (s + 0x6D2B79F5) & M32
t = ((s ^ (s >> 15)) * (s | 1)) & M32
u = ((t ^ (t >> 7)) * (t | 61)) & M32
t = (t ^ ((t + u) & M32)) & M32
return (t ^ (t >> 14)) / 4294967296
return draw
def shuffled(n, seed):
draw, order = mulberry32(seed), list(range(n))
for i in range(n - 1, 0, -1):
j = int(draw() * (i + 1))
order[i], order[j] = order[j], order[i]
return order
print(shuffled(n, 1)[:5])
The book's kernel gives the order 247, 339, 281, 485, 529 for the first five of seed 1.
Step 6: Stochastic and Mini-Batch Descent
Many Steps per Epoch
Each epoch shuffles with seed and steps once per batch, cut in turn from the order.
def sgd(A, y, lr, epochs, batch, seed):
theta = np.zeros(A.shape[1])
for ep in range(epochs):
order = shuffled(len(y), seed + ep)
for s in range(0, len(y), batch):
rows = order[s:s + batch]
Ab, yb = A[rows], y[rows]
e = Ab @ theta - yb
theta = theta - lr * 2 / len(yb) * Ab.T @ e
return theta
for m in [1, 8, 56, n]:
b, wz = sgd(Az, y, 0.03, 10, m, 1)
print(m, wz / x.std())
The book's kernel gives, at a rate of 0.03 and seed 1 after 10 epochs, β0.542 v/v per g/cc one sample at a time, β0.530 in mini-batches of 8, β0.519 in mini-batches of 56 and β0.240 on the full batch of 616.
Step 7: The Expected Gradient
Noise About the Full Gradient
The loss is a mean over the samples, so its gradient is the mean of the samples' gradients. The batches of one epoch hold every sample once, so their gradients, averaged, are the full gradient exactly; a batch drawn at random is the full gradient on average.
order = shuffled(n, 1)
grads = []
for s in range(0, n, 8):
rows = order[s:s + 8]
grads.append(-2 / 8 * Az[rows].T @ y[rows])
full = -2 / n * Az.T @ y
print(np.mean(grads, axis=0), full)
The book's kernel gives, at zero weights, a full gradient of β0.4641 in the intercept and +0.0672 in the standardized slope, and the 77 batches' gradients average to the same; they lie about it at a root mean square distance of 0.136, against 0.419 one sample at a time and 0.036 in batches of 56.
Step 8: Replay
The Same Seed, the Same Run
A run with a seed is a run anyone can repeat.
run1 = sgd(Az, y, 0.03, 10, 8, 1)
run2 = sgd(Az, y, 0.03, 10, 8, 1)
print((run1 == run2).all())
b, wz = sgd(Az, y, 0.03, 10, 8, 2)
print(wz / x.std())
The book's kernel gives the same run twice, and with seed 2 a slope of β0.533 v/v per g/cc: another order, another path, about the same answer.
What the Noise Costs
With a constant rate the noise never dies: one sample at a time at 0.10 ends 10 epochs at an RMSE of 0.0154 v/v, at 0.01 at 0.0151, against least squares' 0.0149. A smaller rate wanders less and starts slower; a schedule that lowers the rate as the run goes on gets both. On 616 samples the full batch is cheap and exact. On the millions of samples a network trains on, one full gradient is too dear, and mini-batches are how networks are trained.