A Ladder of Learning Rates

OptimizersMedium+20 XP+20

A Ladder of Learning Rates

The learning rate is the most important dial in training, and the usual way to set it is not theory but a quick experiment. Try a ladder of rates, each a fixed multiple of the last, give each one a short run, and watch three behaviours appear in order: crawling, working, then blowing up.

Run that experiment on a straight-line model y^=wx+b\hat y = w x + by^​=wx+b, fitted by mean squared error to nnn points. Its gradients are

∂L∂w=2n∑i(y^i−yi) xi,∂L∂b=2n∑i(y^i−yi)\frac{\partial L}{\partial w} = \frac{2}{n}\sum_{i} (\hat y_i - y_i)\, x_i, \qquad \frac{\partial L}{\partial b} = \frac{2}{n}\sum_{i} (\hat y_i - y_i)∂w∂L​=n2​i∑​(y^​i​−yi​)xi​,∂b∂L​=n2​i∑​(y^​i​−yi​)

Task: write rate_sweep(xs, ys, start_rate, factor, max_rates, steps).

  • The rates tried are start_rate, start_rate * factor, start_rate * factor**2, and so on: at most max_rates of them, in that order.
  • Each rate gets its own short run from scratch: start at w=b=0w = b = 0w=b=0, then take steps steps of gradient descent using all the points at once. In every step, compute both gradients at the current (w,b)(w, b)(w,b) before changing either one. The rate's result is the MSE after its last step.
  • The starting loss is the MSE at w=b=0w = b = 0w=b=0. A rate blows up if its result is larger than the starting loss. The first rate that blows up ends the sweep: it is not recorded, and no larger rate is tried.

Return a tuple (chosen, losses):

  • losses is the result of every recorded rate, in the order tried, each rounded to 4 decimal places.
  • chosen is the recorded rate with the lowest result (on a tie, the smaller rate), rounded to 4 decimal places, or None if the very first rate blew up.

Examples

xs = [1.0, 2.0, 3.0, 4.0]
ys = [3.0, 5.0, 7.0, 9.0]
start_rate = 0.001
factor = 2
max_rates = 10
steps = 20
returns (0.064, [20.9099, 10.5448, 2.5929, 0.1447, 0.0115, 0.0093, 0.0063])
xs = [-1.0, 0.0, 1.0, 2.0]
ys = [0.5, 1.0, 2.5, 3.0]
start_rate = 0.02
factor = 3
max_rates = 12
steps = 10
returns (0.18, [1.0535, 0.1274, 0.0509, 1.5229])

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run