What is an Optimizer?
The optimizer is the algorithm that updates the weights using the gradients. Gradient descent is the basic idea, and different optimizers improve it in clever ways.
Popular Optimizers
| Optimizer | Idea | When to use |
| SGD | Basic gradient descent on small batches | Simple problems, when you want full control |
| SGD with momentum | Keeps moving in a useful direction like a rolling ball | Often better than plain SGD |
| RMSprop | Adapts the step size for each weight | Recurrent networks |
| Adam | Momentum plus adaptive step sizes | Best default for most problems |
| AdamW | Adam with better weight decay | Transformers and large models |
Beginner rule: When in doubt, use Adam with the default learning rate 0.001. It works well in most cases.
Using Optimizers in Keras
python
import keras
# As a string: default settings
model.compile(optimizer="adam", loss="mse")
# As an object: change the settings
opt = keras.optimizers.Adam(learning_rate=0.001)
model.compile(optimizer=opt, loss="mse")
sgd = keras.optimizers.SGD(learning_rate=0.01, momentum=0.9)
rms = keras.optimizers.RMSprop(learning_rate=0.001)
adamw = keras.optimizers.AdamW(learning_rate=0.001, weight_decay=0.004)
Learning Rate Schedules
A big learning rate helps at the start. A small one helps to fine-tune at the end. A schedule reduces the learning rate over time.
python
schedule = keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate=0.01,
decay_steps=1000,
decay_rate=0.9
)
opt = keras.optimizers.Adam(learning_rate=schedule)
Another practical way is the ReduceLROnPlateau callback, which lowers the learning rate automatically when the validation loss stops improving. You will learn callbacks in a later lesson.
Comparing Optimizers Experiment
python
import keras
from keras import layers
(x_train, y_train), _ = keras.datasets.mnist.load_data()
x_train = x_train.astype("float32") / 255.0
def build():
return keras.Sequential([
keras.Input(shape=(28, 28)),
layers.Flatten(),
layers.Dense(64, activation="relu"),
layers.Dense(10, activation="softmax"),
])
for name in ["sgd", "rmsprop", "adam"]:
model = build()
model.compile(optimizer=name, loss="sparse_categorical_crossentropy", metrics=["accuracy"])
h = model.fit(x_train, y_train, epochs=3, batch_size=64, validation_split=0.1, verbose=0)
print(name, round(h.history["val_accuracy"][-1], 4))
Result
Adam usually reaches a higher validation accuracy than plain SGD in only 3 epochs.
Tip: The learning rate is the most important setting. If your loss is not decreasing or becomes NaN, try a smaller learning rate such as 0.0001.
Conclusion
Adam is a great default. Try SGD with momentum when you want a classic approach, and use learning rate schedules for better final accuracy.
Quick Summary: Optimizers update the weights. Start with Adam at 0.001, and adjust the learning rate if training is unstable or slow.