AI Foundations for Developers COURSE·LESSON 06 OF 410 completed

Loss, Gradients, and Optimization

Learning as error reduction

A model makes a prediction, a loss function measures its error, and an optimizer adjusts parameters. Loss must suit the task: squared error for a simple regression example, cross-entropy for classification, and task-specific objectives elsewhere.

For the one-parameter model prediction = w×x, define loss = (prediction-y)². Its derivative with respect to w is 2x(wx-y). The derivative tells us how the loss changes for a small change in the weight.

Gradient descent updates w = w - learning_rate×gradient. We subtract the gradient to move locally downhill. It does not guarantee finding the global best solution in a complex neural network.

Trace one update

Let x=2, y=6, w=1, learning rate 0.1. Prediction is 2 and loss is 16. The gradient is 2×2×(2-6)=-16. The new weight is 1-0.1×(-16)=2.6. The new prediction is 5.2 and loss is 0.64.

python
w = 1.0
x, y = 2.0, 6.0
for step in range(5):
    prediction = w * x
    loss = (prediction - y) ** 2
    print(step, round(w, 4), round(loss, 4))
    gradient = 2 * x * (prediction - y)
    w -= 0.1 * gradient

Run it in the Python compiler, then try a learning rate of 1.0. The weight oscillates and the loss grows: a large step can overshoot the useful region.

The practical training loop

Rendering diagram…
flowchart LR
  A[Batch of examples] --> B[Forward predictions]
  B --> C[Compute loss]
  C --> D[Backward gradients]
  D --> E[Optimizer update]
  E --> B

An epoch is one pass through the training dataset. A batch is the group used for one update. Mini-batches trade noisy gradients for manageable memory and efficient computation. Optimizers such as SGD with momentum and Adam use additional state to shape updates. Learning-rate schedules change the step size during training. Gradient clipping limits unusually large gradients; it does not fix all instability.

Checkpoint with answers

Are a parameter and a hyperparameter the same? No. A weight is learned during training; a learning rate is chosen as part of the training configuration.

Why can falling training loss still produce a bad model? The model may overfit or optimize a proxy that does not reflect real usefulness.

Exercise: With gradient -4 and learning rate 0.05, how does a weight change? Answer: it increases by 0.2.

Learn at your own pace0 / 41 lessons complete