Artificial Intelligence • Mathematical Foundations • 19 min read

Optimization and Gradient Descent

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, ww. The current value is w=8w=8, but for a simple toy objective the best value would be w=3w=3. We need a repeatable rule for adjusting ww 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 J(w)=(w−3)2J(w)=(w-3)^2, the derivative is J′(w)=2(w−3)J'(w)=2(w-3). At w=8w=8, the derivative is 10. With learning rate 0.10.1, one update gives:

wnew=8−0.1(10)=7.w_{\text{new}} = 8 - 0.1(10) = 7.

The objective falls from 2525 to 1616. 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 θ\boldsymbol{\theta}:

min⁡θJ(θ)\min_{\boldsymbol{\theta}} J(\boldsymbol{\theta})

Here:

  • θ\boldsymbol{\theta} contains the adjustable model parameters.
  • JJ is the objective function that the training process tries to minimize.
  • The optimization algorithm proposes parameter updates intended to reduce JJ.

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.

TermWhat it measures or controlsExample
Loss functionError or mismatch associated with predictions, sometimes on an individual exampleSquared prediction error
Training objectiveQuantity optimized during training; may aggregate losses and include regularizationMean squared error plus a penalty on large weights
Evaluation metricCriterion used to judge model performanceClassification accuracy or mean absolute error
ParameterValue adjusted by the optimizerRegression weight ww
HyperparameterConfiguration set outside the parameter-update processLearning rate η\eta

For predictions y^i\hat{y}_i and targets yiy_i, a common mean squared error is:

MSE⁡(θ)=1n∑i=1n(y^i−yi)2\operatorname{MSE}(\boldsymbol{\theta}) =\frac{1}{n}\sum_{i=1}^{n}(\hat{y}_i-y_i)^2

A related objective uses 1/(2n)1/(2n) instead of 1/n1/n. 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:

J(θ)=1n∑i=1nℓ(y^i,yi)+λR(θ)J(\boldsymbol{\theta}) =\frac{1}{n}\sum_{i=1}^{n}\ell(\hat{y}_i,y_i) +\lambda R(\boldsymbol{\theta})

where ℓ\ell is a per-example loss, RR is a regularization term, and λ\lambda 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:

∇J(θ)=[∂J∂θ1∂J∂θ2⋮∂J∂θp]\nabla J(\boldsymbol{\theta})= \begin{bmatrix} \frac{\partial J}{\partial \theta_1} \\ \frac{\partial J}{\partial \theta_2} \\ \vdots \\ \frac{\partial J}{\partial \theta_p} \end{bmatrix}

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:

θt+1=θt−η∇J(θt)\boxed{\boldsymbol{\theta}_{t+1} =\boldsymbol{\theta}_t-\eta\nabla J(\boldsymbol{\theta}_t)}

The symbols mean:

  • tt: the current optimization step.
  • θt\boldsymbol{\theta}_t: the parameters before the update.
  • ∇J(θt)\nabla J(\boldsymbol{\theta}_t): the gradient calculated at those parameters.
  • η>0\eta>0: the learning rate, controlling the step size.
  • θt+1\boldsymbol{\theta}_{t+1}: the updated parameters.

For a single parameter ww, the rule becomes:

wt+1=wt−ηdJdw(wt)w_{t+1}=w_t-\eta\frac{dJ}{dw}(w_t)

If the derivative is positive, a positive learning rate moves ww downward. If the derivative is negative, the update moves ww 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:

J(w)=(w−3)2J(w)=(w-3)^2

Its minimum value is 00, attained at w=3w=3. We will pretend that we do not know the best value in advance and try to discover it with gradient descent.

Differentiate:

dJdw=2(w−3)\frac{dJ}{dw}=2(w-3)

Start at w0=0w_0=0 and use a learning rate of η=0.2\eta=0.2.

First update

At w0=0w_0=0, the derivative is 2(0−3)=−62(0-3)=-6. Therefore:

w1=0−0.2(−6)=1.2w_1=0-0.2(-6)=1.2

The objective decreases from J(0)=9J(0)=9 to J(1.2)=3.24J(1.2)=3.24.

Second and third updates

For the second update:

w2=1.2−0.2[2(1.2−3)]=1.92w_2=1.2-0.2\bigl[2(1.2-3)\bigr]=1.92

For the third:

w3=1.92−0.2[2(1.92−3)]=2.352w_3=1.92-0.2\bigl[2(1.92-3)\bigr]=2.352
StepParameter wwGradient 2(w−3)2(w-3)Objective J(w)J(w)
00.000-6.0009.000000
11.200-3.6003.240000
21.920-2.1601.166400
32.352-1.2960.419904

The updates approach w=3w=3. Each step changes the gradient, so the same learning rate produces smaller absolute updates as this particular function approaches its minimum.

Graph of the quadratic objective J(w) = (w minus 3) squared with parameter values 0, 1.2, 1.92, and 2.352 moving toward the minimum at w = 3.
Four gradient descent iterations on the quadratic objective. The marked points approach the minimum, while the objective decreases at each step.

Why these updates converge

For this specific quadratic, substitute the derivative into the update rule:

wt+1=wt−2η(wt−3)w_{t+1}=w_t-2\eta(w_t-3)

Subtracting the optimal value 33 from both sides gives:

wt+1−3=(1−2η)(wt−3)w_{t+1}-3=(1-2\eta)(w_t-3)

The distance from the optimum contracts at every step when ∣1−2η∣<1|1-2\eta|<1, or equivalently when 0<η<10<\eta<1.

  • With η=0.2\eta=0.2, the distance is multiplied by 0.60.6 each step.
  • With η=0.8\eta=0.8, the updates cross the optimum but get closer overall.
  • With η=1\eta=1, the parameter oscillates between equally distant values and does not converge unless it starts at the optimum.
  • With η>1\eta>1, 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 behaviorTypical effectWhat to examine
Too smallTraining makes slow progressIncrease the rate or improve feature scaling
Appropriately chosenObjective generally decreases over trainingContinue monitoring training and validation results
Too largeObjective oscillates, increases, or becomes non-finiteReduce the rate or investigate gradient magnitude
Changes over timeLarge early steps followed by smaller refinementsUse 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 η\eta 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:

y^i=wxi+b\hat{y}_i=wx_i+b

The model has two parameters: weight ww and bias bb. For nn examples, choose the objective:

J(w,b)=12n∑i=1n(wxi+b−yi)2J(w,b)=\frac{1}{2n}\sum_{i=1}^{n}(wx_i+b-y_i)^2

The factor 1/21/2 simplifies the derivatives:

∂J∂w=1n∑i=1nxi(wxi+b−yi)\frac{\partial J}{\partial w}=\frac{1}{n}\sum_{i=1}^{n}x_i(wx_i+b-y_i) ∂J∂b=1n∑i=1n(wxi+b−yi)\frac{\partial J}{\partial b}=\frac{1}{n}\sum_{i=1}^{n}(wx_i+b-y_i)

The optimizer updates both parameters in the same iteration, using gradients computed from the current values:

wt+1=wt−η∂J∂wbt+1=bt−η∂J∂b\begin{aligned} w_{t+1}&=w_t-\eta\frac{\partial J}{\partial w} \\ b_{t+1}&=b_t-\eta\frac{\partial J}{\partial b} \end{aligned}

One manual training step

Suppose the dataset is:

Input xxTarget yy
01
13
25

Start with w=0w=0, b=0b=0, and η=0.1\eta=0.1. All predictions are initially zero, so the residuals y^i−yi\hat{y}_i-y_i are −1-1, −3-3, and −5-5.

The gradients are:

∂J∂w=0(−1)+1(−3)+2(−5)3=−133\frac{\partial J}{\partial w} =\frac{0(-1)+1(-3)+2(-5)}{3} =-\frac{13}{3} ∂J∂b=−1−3−53=−3\frac{\partial J}{\partial b} =\frac{-1-3-5}{3}=-3

After one simultaneous update:

wnew=0−0.1(−133)≈0.4333w_{\text{new}}=0-0.1\left(-\frac{13}{3}\right)\approx0.4333 bnew=0−0.1(−3)=0.3b_{\text{new}}=0-0.1(-3)=0.3

The objective falls from about 5.83335.8333 to 3.38703.3870. With further suitable updates, the parameters approach w=2w=2 and b=1b=1, 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 w=2w=2 and b=1b=1, giving a prediction near 77 for x=3x=3. 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.

MethodData used for each gradient estimateMain trade-off
Full-batch gradient descentEntire training datasetStable dataset gradient but potentially costly per update
Stochastic gradient descent (SGD)One randomly selected example at a timeCheap, noisy updates
Mini-batch gradient descentA subset of examples, such as 32 or 128Balances computational efficiency and gradient noise

For a training set with nn examples, the full-batch gradient of an average loss is:

gfull=1n∑i=1n∇θℓi(θ)g_{\text{full}}=\frac{1}{n}\sum_{i=1}^{n} \nabla_{\boldsymbol{\theta}}\ell_i(\boldsymbol{\theta})

For a mini-batch BB with ∣B∣|B| examples, an estimate is:

gB=1∣B∣∑i∈B∇θℓi(θ)g_B=\frac{1}{|B|}\sum_{i\in B} \nabla_{\boldsymbol{\theta}}\ell_i(\boldsymbol{\theta})

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:

vt+1=βvt+∇J(θt)θt+1=θt−ηvt+1\begin{aligned} \mathbf{v}_{t+1}&=\beta\mathbf{v}_t+\nabla J(\boldsymbol{\theta}_t) \\ \boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t-\eta\mathbf{v}_{t+1} \end{aligned}

Here β\beta 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 0≤α≤10\leq\alpha\leq1:

J(αx+(1−α)y)≤αJ(x)+(1−α)J(y)J(\alpha\mathbf{x}+(1-\alpha)\mathbf{y}) \leq \alpha J(\mathbf{x})+(1-\alpha)J(\mathbf{y})

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.

ConceptMeaning
Local minimumAn objective value no higher than sufficiently nearby values
Global minimumLowest attainable objective value over the specified domain
Saddle pointA stationary point that is not a local minimum or maximum in the usual multidimensional setting
Stationary pointA differentiable point where the gradient is zero
ConvergenceApproaching 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:

  1. Training loss: Is the optimizer reducing the quantity it was designed to minimize?
  2. Validation performance: Are improvements transferring to held-out examples?
  3. Gradient and parameter behavior: Are gradients or parameter values becoming extremely large or non-finite?
  4. 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

SymptomPossible causeUseful diagnostic or response
Loss decreases very slowlyLearning rate is too small; poor conditioningCheck gradient scale and consider feature scaling
Loss jumps up and downLearning rate too large; noisy mini-batchesReduce the rate or examine batch behavior
Loss becomes NaN or infiniteNumerical overflow, unstable computation, invalid inputsInspect data, gradients, loss implementation, and learning rate
Training loss improves, validation gets worseOverfitting or distribution mismatchReview regularization, early stopping, and data splits
Gradients stay near zeroNear-stationary region or vanishing gradientsInspect activations, initialization, and architecture
Model improves little despite low lossTraining objective may not match the real taskReconsider 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

  1. Explain the difference between a loss function, an objective function, and an evaluation metric.
  2. If J(w)=(w−4)2J(w)=(w-4)^2, w0=0w_0=0, and η=0.25\eta=0.25, what is the first gradient descent update?
  3. Why does the gradient appear with a minus sign in the minimization update rule?
  4. A training dataset has 960 examples and uses mini-batches of 64. How many updates occur in one epoch if no examples are dropped?
  5. Why can a point with zero gradient fail to be a global minimum?
  6. If training loss keeps falling but validation error increases, is optimization necessarily failing to minimize the training objective?
Show worked answers
  1. 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.
  2. dJ/dw=2(w−4)dJ/dw=2(w-4), so the initial derivative is −8-8. Thus w1=0−0.25(−8)=2w_1=0-0.25(-8)=2.
  3. The gradient points toward local increase; subtracting it produces a local descent direction when the gradient is nonzero and the step is sufficiently small.
  4. 960/64=15960/64=15 parameter updates per epoch.
  5. The point may be a local maximum, a saddle point, or a local minimum that is not global.
  6. No. The optimizer may be successfully minimizing training loss while the model increasingly overfits or generalizes poorly.

References and further reading

Related articles in

Image preview

Fit