A machine-learning model may start with parameters that produce inaccurate predictions. Training must determine how to change those parameters so that the predictions improve. Optimization provides the mathematical methods for making those changes, and gradient descent is one of the most important of those methods.
Optimization does not tell a model what the correct answer is. Instead, it searches for parameter values that perform well according to a chosen objective. The objective, the available data, and the optimization method jointly determine what the model learns.
This article builds on Derivatives, Gradients, and the Chain Rule and Vector and Matrix Operations. It focuses on the mechanics of optimization before introducing more sophisticated neural-network training methods.
Start with an adjustable prediction
Suppose a model predicts an exam score using a single number, . The current value is , but for a simple toy objective the best value would be . We need a repeatable rule for adjusting instead of guessing randomly.
Imagine a landscape where height means prediction error. When you are on a slope, moving a small distance downhill usually lowers the error. A gradient is the mathematical description of the local uphill direction, so gradient descent moves in the opposite direction. The size of the move is controlled by the learning rate.
For the example objective , the derivative is . At , the derivative is 10. With learning rate , one update gives:
The objective falls from to . That is progress, not an instant solution. Repeated steps continue to adjust the parameter. Real AI models have many parameters and more complicated error surfaces, but the basic update principle is the same.
The key questions in this article are: What is being minimized? How is the direction calculated? How large should each step be? And how do we know training is working?
What is optimization?
Mathematical optimization is the process of finding values of decision variables that minimize or maximize a specified objective, possibly subject to constraints.
In machine learning, the decision variables are usually the learnable parameters of a model, such as the coefficients of a regression equation or the weights of a neural network. We commonly write the objective as a function of the parameter vector :
Here:
- contains the adjustable model parameters.
- is the objective function that the training process tries to minimize.
- The optimization algorithm proposes parameter updates intended to reduce .
Some problems are naturally stated as maximization, such as maximizing a likelihood or expected reward. When mathematically appropriate, a maximization objective can be rewritten as a minimization objective by changing its sign.
Objective functions, loss functions, and evaluation metrics
These terms are related but not interchangeable.
| Term | What it measures or controls | Example |
|---|---|---|
| Loss function | Error or mismatch associated with predictions, sometimes on an individual example | Squared prediction error |
| Training objective | Quantity optimized during training; may aggregate losses and include regularization | Mean squared error plus a penalty on large weights |
| Evaluation metric | Criterion used to judge model performance | Classification accuracy or mean absolute error |
| Parameter | Value adjusted by the optimizer | Regression weight |
| Hyperparameter | Configuration set outside the parameter-update process | Learning rate |
For predictions and targets , a common mean squared error is:
A related objective uses instead of . Both have the same minimizers, but their gradients differ by a factor of two. This convention is often chosen to simplify derivatives. Always check which definition a formula or software library uses.
For a regularized model, an objective might be:
where is a per-example loss, is a regularization term, and controls its influence. Regularization may discourage some parameter configurations even if they fit the training data closely.
Important: A smaller training objective does not automatically imply better performance on unseen data. Generalization must be checked with an appropriate validation or test procedure.
How gradients guide optimization
A derivative describes how a function changes with one variable. For an objective with multiple parameters, the gradient collects its partial derivatives:
At a differentiable point, the gradient points in the direction of the steepest local increase under the usual Euclidean geometry. Its negative therefore gives a direction of local decrease. This does not guarantee that an arbitrarily large step in that direction will improve the objective.
The gradient descent update rule
Gradient descent is an iterative optimization method that updates parameters by taking steps opposite to the objective’s gradient:
The symbols mean:
- : the current optimization step.
- : the parameters before the update.
- : the gradient calculated at those parameters.
- : the learning rate, controlling the step size.
- : the updated parameters.
For a single parameter , the rule becomes:
If the derivative is positive, a positive learning rate moves downward. If the derivative is negative, the update moves upward. The aim is to move toward lower objective values, not necessarily toward smaller parameter values.
Worked example: minimize a simple function
Consider the objective:
Its minimum value is , attained at . We will pretend that we do not know the best value in advance and try to discover it with gradient descent.
Differentiate:
Start at and use a learning rate of .
First update
At , the derivative is . Therefore:
The objective decreases from to .
Second and third updates
For the second update:
For the third:
| Step | Parameter | Gradient | Objective |
|---|---|---|---|
| 0 | 0.000 | -6.000 | 9.000000 |
| 1 | 1.200 | -3.600 | 3.240000 |
| 2 | 1.920 | -2.160 | 1.166400 |
| 3 | 2.352 | -1.296 | 0.419904 |
The updates approach . Each step changes the gradient, so the same learning rate produces smaller absolute updates as this particular function approaches its minimum.
Why these updates converge
For this specific quadratic, substitute the derivative into the update rule:
Subtracting the optimal value from both sides gives:
The distance from the optimum contracts at every step when , or equivalently when .
- With , the distance is multiplied by each step.
- With , the updates cross the optimum but get closer overall.
- With , the parameter oscillates between equally distant values and does not converge unless it starts at the optimum.
- With , the distance grows in this example.
These numerical thresholds apply only to this objective as written. Different objectives have different stable learning-rate ranges, and a step that is too large can make training diverge.
The learning rate
The learning rate is a hyperparameter that controls how aggressively the optimizer updates parameters. It is often one of the most consequential settings in model training.
| Learning-rate behavior | Typical effect | What to examine |
|---|---|---|
| Too small | Training makes slow progress | Increase the rate or improve feature scaling |
| Appropriately chosen | Objective generally decreases over training | Continue monitoring training and validation results |
| Too large | Objective oscillates, increases, or becomes non-finite | Reduce the rate or investigate gradient magnitude |
| Changes over time | Large early steps followed by smaller refinements | Use a suitable learning-rate schedule |
The learning rate is not a universal measure of how much the objective decreases. Its effect depends on the gradient, the objective’s curvature, parameter scaling, and the algorithm being used.
Learning-rate schedules
A learning-rate schedule changes during training. Common strategies include a fixed rate, reductions at predefined milestones, gradual decay, or reducing the rate when validation progress stalls.
The purpose is to balance faster initial progress against finer updates later. A schedule does not replace the need to choose a sensible initial rate.
Applying gradient descent to machine learning
Consider a simple linear regression model:
The model has two parameters: weight and bias . For examples, choose the objective:
The factor simplifies the derivatives:
The optimizer updates both parameters in the same iteration, using gradients computed from the current values:
One manual training step
Suppose the dataset is:
| Input | Target |
|---|---|
| 0 | 1 |
| 1 | 3 |
| 2 | 5 |
Start with , , and . All predictions are initially zero, so the residuals are , , and .
The gradients are:
After one simultaneous update:
The objective falls from about to . With further suitable updates, the parameters approach and , the line that fits this small dataset exactly.
This shows the relationship between an objective, its derivatives, and a concrete training step. Neural networks use the same broad idea, although backpropagation computes gradients through many interconnected operations.
Implementing gradient descent in Python
The first example minimizes the earlier quadratic function without any machine-learning library.
def objective(w):
return (w - 3.0) ** 2
def derivative(w):
return 2.0 * (w - 3.0)
w = 0.0
learning_rate = 0.2
for step in range(4):
print(f"step={step} w={w:.3f} loss={objective(w):.6f}")
w -= learning_rate * derivative(w)
Expected output:
step=0 w=0.000 loss=9.000000
step=1 w=1.200 loss=3.240000
step=2 w=1.920 loss=1.166400
step=3 w=2.352 loss=0.419904
Training linear regression with NumPy
The next example uses a dataset, two parameters, and full-batch gradient descent. NumPy performs the numerical calculations, but the training update is implemented directly so that each part remains visible.
import numpy as np
x = np.array([0.0, 1.0, 2.0])
y = np.array([1.0, 3.0, 5.0])
w = 0.0
b = 0.0
learning_rate = 0.1
n = len(x)
for step in range(1000):
predictions = w * x + b
residuals = predictions - y
# Objective: (1 / (2n)) * sum(residual**2)
grad_w = np.sum(x * residuals) / n
grad_b = np.sum(residuals) / n
# Update both parameters using the same set of gradients.
w = w - learning_rate * grad_w
b = b - learning_rate * grad_b
if step in (0, 9, 99, 999):
loss = np.mean((w * x + b - y) ** 2) / 2
print(f"step={step + 1:4d} loss={loss:.6f}")
print(f"weight={w:.3f}, bias={b:.3f}")
print(f"prediction for x=3: {w * 3 + b:.3f}")
The final parameter values should be close to and , giving a prediction near for . The code recalculates both gradients before updating either parameter, as required by the simultaneous gradient-descent rule.
Note: This tiny, perfectly linear dataset is deliberately chosen for explanation. Real datasets have noise, sampling uncertainty, and other complications. A low training error does not itself demonstrate that a model will generalize.
Batch, stochastic, and mini-batch gradient descent
The phrase gradient descent describes a general update principle. In machine learning, an important practical distinction is how much training data contributes to an individual update.
| Method | Data used for each gradient estimate | Main trade-off |
|---|---|---|
| Full-batch gradient descent | Entire training dataset | Stable dataset gradient but potentially costly per update |
| Stochastic gradient descent (SGD) | One randomly selected example at a time | Cheap, noisy updates |
| Mini-batch gradient descent | A subset of examples, such as 32 or 128 | Balances computational efficiency and gradient noise |
For a training set with examples, the full-batch gradient of an average loss is:
For a mini-batch with examples, an estimate is:
The mini-batch gradient generally differs from the full-dataset gradient. If the batch is sampled appropriately and each example is equally likely, it can be an unbiased estimate of the full-data average gradient. Regularization terms can be handled separately.
Batch size, epoch, and optimization step
- Batch size: Number of training examples used in one mini-batch update.
- Optimization step: One gradient calculation and parameter update.
- Epoch: One complete pass through the training dataset, under the standard epoch-based training convention.
For example, 1,000 examples with a batch size of 100 normally produce 10 updates per epoch. If the batch size is 128, the final batch may contain fewer examples unless it is dropped or padded.
Batch size also affects device utilization, memory usage, and training behavior. Larger batches are not automatically better, and the learning rate may need reconsideration when changing batch size.
Improving the basic optimizer
Plain gradient descent is an essential starting point, but practical training often uses extensions.
Momentum
Momentum combines the current gradient with accumulated information from earlier gradients. It can reduce inefficient back-and-forth motion in some directions and accelerate progress along others.
One common form is:
Here controls how strongly earlier gradients influence the update. Implementations vary in how they define and initialize the momentum state, so formulas must be compared with the conventions of the relevant framework.
Adaptive optimizers
Algorithms such as AdaGrad, RMSProp, and Adam adapt aspects of the parameter updates using information from previous gradients. Adam combines moving averages of gradients and squared gradients, with bias correction in its usual formulation.
Adaptive optimization methods can be useful, but no optimizer is best for every problem. Optimizer choice, learning rate, data representation, and evaluation protocol must be considered together. The details are developed further in Training Neural Networks: Loss, Optimizers, and Regularization.
Feature scaling and gradient clipping
When input features differ greatly in numerical scale, the objective can be poorly conditioned. For gradient-based training, feature standardization and scaling often make optimization easier and more predictable.
Gradient clipping limits the magnitude or norm of calculated gradients before an update. It can mitigate extremely large updates, particularly in certain deep learning settings, but it does not fix a fundamentally unsuitable objective or poor data.
Convex and non-convex optimization
An objective is convex over a convex domain when the straight line segment joining any two points on its graph lies on or above the graph. In notation, for :
For a differentiable convex objective, every local minimum is also a global minimum. This property makes optimization easier to analyze, although numerical behavior still depends on step sizes and problem conditioning.
Neural-network training objectives are generally non-convex. They can have different local minima, saddle points, and regions with very small gradients. Gradient descent may reach a useful solution without locating the global minimum.
| Concept | Meaning |
|---|---|
| Local minimum | An objective value no higher than sufficiently nearby values |
| Global minimum | Lowest attainable objective value over the specified domain |
| Saddle point | A stationary point that is not a local minimum or maximum in the usual multidimensional setting |
| Stationary point | A differentiable point where the gradient is zero |
| Convergence | Approaching a limiting state under the method’s assumptions and stopping conditions |
A zero gradient does not prove that the point is a global minimum. Depending on the objective, it might indicate a minimum, maximum, or saddle point.
When gradient descent is appropriate
Gradient-based methods are natural for models whose training objectives are differentiable or have usable subgradients almost everywhere. Examples include linear models, logistic regression, and many neural networks.
They are not the only way to optimize an AI system. Other methods include closed-form solutions, coordinate methods, constrained optimization algorithms, tree-based learning procedures, evolutionary search, and derivative-free optimization. Many decision-tree training algorithms, for example, select splits using discrete criteria rather than updating tree parameters by backpropagating gradients.
The correct optimization method depends on the objective, parameter structure, constraints, data size, available computation, and required reliability.
Monitoring and stopping training
An optimizer needs a stopping condition. Common criteria include a fixed number of steps, a sufficiently small improvement in the objective, a sufficiently small gradient norm, a time or compute budget, or early stopping based on validation performance.
A practical training process typically monitors:
- Training loss: Is the optimizer reducing the quantity it was designed to minimize?
- Validation performance: Are improvements transferring to held-out examples?
- Gradient and parameter behavior: Are gradients or parameter values becoming extremely large or non-finite?
- Compute cost: Are further updates worth the time and resources?
Early stopping based on validation data is a model-selection decision. The final test set should remain separate and should not be repeatedly used to tune the stopping point or learning rate.
Common optimization problems
| Symptom | Possible cause | Useful diagnostic or response |
|---|---|---|
| Loss decreases very slowly | Learning rate is too small; poor conditioning | Check gradient scale and consider feature scaling |
| Loss jumps up and down | Learning rate too large; noisy mini-batches | Reduce the rate or examine batch behavior |
Loss becomes NaN or infinite | Numerical overflow, unstable computation, invalid inputs | Inspect data, gradients, loss implementation, and learning rate |
| Training loss improves, validation gets worse | Overfitting or distribution mismatch | Review regularization, early stopping, and data splits |
| Gradients stay near zero | Near-stationary region or vanishing gradients | Inspect activations, initialization, and architecture |
| Model improves little despite low loss | Training objective may not match the real task | Reconsider targets, metric, data, and problem formulation |
These symptoms have multiple possible explanations. Changing the learning rate without checking the data and implementation can hide the underlying problem.
Common misconceptions
“Gradient descent always finds the best possible parameters.” Not necessarily. Its guarantees depend on the objective and assumptions, and non-convex optimization typically has no general guarantee of a global optimum.
“A larger learning rate always trains faster.” It can increase the size of individual updates, but may produce oscillation or divergence rather than faster progress.
“The gradient is the same as the loss.” The loss is the objective’s value; the gradient describes how that value changes with parameters.
“SGD means every update uses the entire dataset.” In its strict form, SGD uses an individual sampled example. In machine-learning practice, the term is also used for mini-batch variants.
“A model with zero training loss is necessarily reliable.” It may simply fit the training examples, including noise or accidental patterns. Evaluation on independent data remains necessary.
Check your understanding
- Explain the difference between a loss function, an objective function, and an evaluation metric.
- If , , and , what is the first gradient descent update?
- Why does the gradient appear with a minus sign in the minimization update rule?
- A training dataset has 960 examples and uses mini-batches of 64. How many updates occur in one epoch if no examples are dropped?
- Why can a point with zero gradient fail to be a global minimum?
- If training loss keeps falling but validation error increases, is optimization necessarily failing to minimize the training objective?
Show worked answers
- A loss measures prediction mismatch, an objective is the quantity optimized and may combine several terms, and an evaluation metric judges model performance against the intended task.
- , so the initial derivative is . Thus .
- The gradient points toward local increase; subtracting it produces a local descent direction when the gradient is nonzero and the step is sufficiently small.
- parameter updates per epoch.
- The point may be a local maximum, a saddle point, or a local minimum that is not global.
- No. The optimizer may be successfully minimizing training loss while the model increasingly overfits or generalizes poorly.
Related concepts
- Derivatives, Gradients, and the Chain Rule provides the calculus used to compute parameter gradients.
- Vector and Matrix Operations explains multidimensional representations and numerical calculations.
- Probability and Bayes’ Theorem introduces uncertainty used in probabilistic model objectives.
- Entropy, Cross-Entropy, and KL Divergence examines information-theoretic quantities used in training objectives.
- Feature Engineering, Encoding, and Scaling develops data transformations that can affect optimization.
- Linear and Logistic Regression applies optimization to classical predictive models.
- Forward Propagation and Backpropagation explains neural-network gradient computation.
- Training Neural Networks: Loss, Optimizers, and Regularization extends these ideas to modern deep learning.
- Model Training, Overfitting, and Generalization distinguishes successful fitting from generalization.
- AI Knowledge Map connects this article to the wider learning path.
References and further reading
- Google Machine Learning Crash Course — practical introduction to model training, loss functions, and gradient descent.
- Google Deep Learning Tuning Playbook: Optimizer update rules — equations for SGD, momentum, and adaptive optimizers.
- PyTorch SGD Documentation — the API and implementation conventions of stochastic gradient descent with momentum.
- NumPy Documentation — numerical array operations used in the code examples.
- Deep Learning, Chapter 8: Optimization for Training Deep Models — theoretical background on optimization in deep learning.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.