The learning rate controls the scale of a parameter update during training. It is a hyperparameter supplied to Optimisers.
Effect on training
| Learning rate | Possible result |
|---|---|
| Too large | Updates pass over a useful solution, and loss can rise or oscillate |
| Too small | The model makes slow progress within the available training time |
| Suitable | Training makes steady progress toward lower loss |
A rate such as 0.001 is a starting value to test. The suitable value depends on the model, data, and optimiser.
One update
For plain SGD:
The symbols mean:
- is the current parameter
- is its gradient
- is the learning rate
Suppose and :
| Learning rate | Update size | New parameter |
|---|---|---|
Adam also uses gradient history to scale its updates. Its learning rate still controls the overall update scale.
Code
PyTorch
This example performs the first row of the table:
import torch
w = torch.nn.Parameter(torch.tensor(2.0))
optimizer = torch.optim.SGD([w], lr=0.1)
optimizer.zero_grad()
loss = 0.4 * w
loss.backward()
optimizer.step()
print(round(w.item(), 3))1.96Read the update:
Parametermakeswtrainable[w]is the list of parameters passed to the optimiser- The derivative of
0.4 * wis0.4, sobackward()stores this value inw.grad lr=0.1makesstep()subtract0.04fromw
For a full model, the same setting is torch.optim.Adam(model.parameters(), lr=1e-3).
TensorFlow and Keras
import numpy as np
import tensorflow as tf
X = np.array([[0.], [1.]], dtype="float32")
y = np.array([[0.], [2.]], dtype="float32")
model = tf.keras.Sequential([
tf.keras.Input(shape=(1,)),
tf.keras.layers.Dense(1),
])
optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3)
model.compile(optimizer=optimizer, loss="mse")
model.fit(X, y, batch_size=2, epochs=1, verbose=0)Read the settings:
Xcontains 2 input samples andycontains their target valueslearning_rate=1e-3belongs to the optimiser constructorcompile()gives the model this configured optimiserfit()receives training settings such asbatch_sizeandepochs
The current Keras optimiser API accepts learning_rate. The fit API accepts the data and training settings.
To change an existing constant learning rate before further training:
optimizer.learning_rate.assign(1e-4)This changes the rate from 0.001 to 0.0001. The model keeps its learned weights.