Lab 3 of 3about 45 minutes
Batches, momentum and Adam, written by hand
It uses what you learned in Stochastic gradient descent and Momentum and Adam.
Start here
Run itThe penguins' line from this course: x is each flipper in centimetres past 20 cm, and mass each weight in kilograms. loss and arrow give the line's loss and its uphill arrow on the penguins you hand them: all of them, or a batch. angle gives the angle between two arrows in degrees, from their cosine similarity, as in Linear Algebra for AI.
1The full arrow
Run itFrom Stochastic gradient descent
Start where a model knows nothing, at (0, 0). Run the cell: it prints the loss there, and the full arrow, the average of all 342 penguins' pulls. A plain step works this out from every penguin, every time.
2Deal the batches
Your turnFrom Stochastic gradient descent
Now deal the penguins into mini-batches. rng.permutation(342) gives the numbers 0 to 341 in a random order. Write deal: shuffle, then cut that order into batches of 32, the last one smaller. The cell then counts each batch's arrow by its size, and averages.
Now deal them in the file's own order, with no shuffle.
The file lists the penguins kind by kind, so each batch is mostly one kind, and its arrow points far from the full one.
Hint
Keep rng.permutation(len(x)) in order. Then a list of order[start:start + size], with start going up by size.
One way to do it
def deal(rng, size=32):
order = rng.permutation(len(x))
return [order[start:start + size] for start in range(0, len(x), size)]
batches = deal(np.random.default_rng(7))
arrows = [arrow([0, 0], x[batch], mass[batch]) for batch in batches]
sizes = [len(batch) for batch in batches]
together = sum(size * one for size, one in zip(sizes, arrows)) / 342
print(sizes, together.round(2))3Epochs
On your ownFrom Stochastic gradient descent
On your own now. Write sgd(epochs, rate=0.1): make rng = np.random.default_rng(7) once, then each epoch deal a fresh shuffle and take one plain step on each batch's arrow. It gives back the weights, and the loss on all 342 after every step. Run three epochs and draw the losses.
Hint
Two loops: the epochs outside, and for batch in deal(rng) inside. The step is lab 1's, on x[batch] and mass[batch].
One way to do it
def sgd(epochs, rate=0.1):
rng = np.random.default_rng(7)
weights = np.zeros(2)
losses = []
for _ in range(epochs):
for batch in deal(rng):
weights = weights - rate * arrow(weights, x[batch], mass[batch])
losses.append(loss(weights, x, mass))
return weights, losses
weights, losses = sgd(3)
plt.plot(losses)
print(weights.round(2), round(float(losses[10]), 3), round(float(losses[-1]), 3))4Momentum
Your turnFrom Momentum and Adam
Now the flipper in millimetres from 200 mm, as in calc-momentum-adam: the bowl becomes a long valley. Run the plain steps first, fifty at 0.005, the most this valley takes.
b has crept to 1.64, and the bottom is at 4.16. Now momentum: step keeps 0.9 of itself and adds the new arrow, and the weights move the rate times step.
Hint
First the new step, from the old one and arrow(weights, mm, mass). Then the weights, against it.
One way to do it
def momentum(rate, steps=50):
weights = np.zeros(2)
step = np.zeros(2)
losses = [loss(weights, mm, mass)]
for _ in range(steps):
step = 0.9 * step + arrow(weights, mm, mass)
weights = weights - rate * step
losses.append(loss(weights, mm, mass))
return weights, losses5Adam
Your turnFrom Momentum and Adam
Adam keeps two running averages for each weight: m of its arrows, keeping 0.9 of itself, and s of their squares, keeping 0.999. Write the two. The step line is given: it divides m by the square root of s, and the two 1 - … ** t fix the first steps, when both averages start at zero.
The three side by side, and Adam at its default, 0.001.
At 0.001 Adam hardly moves: it has a learning rate too.
Hint
A running average keeps a share of itself and adds the rest from the new value: 0.9 and 0.1 for m, 0.999 and 0.001 for s, with g ** 2.
One way to do it
def adam(rate, steps=50):
weights = np.zeros(2)
m, s = np.zeros(2), np.zeros(2)
losses = [loss(weights, mm, mass)]
for t in range(1, steps + 1):
g = arrow(weights, mm, mass)
m = 0.9 * m + 0.1 * g
s = 0.999 * s + 0.001 * g ** 2
weights = weights - rate * (m / (1 - 0.9 ** t)) / (np.sqrt(s / (1 - 0.999 ** t)) + 1e-8)
losses.append(loss(weights, mm, mass))
return weights, losses6Adam on mini-batches
On your ownFrom Stochastic gradient descent and Momentum and Adam
On your own now, both lessons at once: Adam on mini-batches, in millimetres. Deal ten epochs of batches from np.random.default_rng(7), and take one Adam step at a rate of 0.1 on each batch's arrow: 110 steps. Keep the weights in batch_adam, and the loss on all 342 at the end in batch_loss.
Hint
Your adam loop, inside a loop over the epochs and deal(rng), with arrow(weights, mm[batch], mass[batch]). Count t across every step, not from 1 each epoch.
One way to do it
rng = np.random.default_rng(7)
weights, m, s, t = np.zeros(2), np.zeros(2), np.zeros(2), 0
for _ in range(10):
for batch in deal(rng):
t += 1
g = arrow(weights, mm[batch], mass[batch])
m = 0.9 * m + 0.1 * g
s = 0.999 * s + 0.001 * g ** 2
weights = weights - 0.1 * (m / (1 - 0.9 ** t)) / (np.sqrt(s / (1 - 0.999 ** t)) + 1e-8)
batch_adam = weights
batch_loss = loss(weights, mm, mass)
print(batch_adam.round(3), round(float(batch_loss), 3))Run on Pyodide 314, Python 3.14, NumPy 2.4, pandas 3.0 and matplotlib 3.10. Checked on .
